這是我當前的設定,它可以作業,但這會增加 init 檔案的容量。我應該如何構建它,以便我的 API 位于其自己的檔案夾中并正確運行?當我將 testapi.py 放在與 run.py 相同的級別時,我無法匯入任何模型。
├── my_frame
│ ├── __init__.py
│ ├── forms.py
│ ├── models.py
│ ├── routes.py
│ ├── site.db
│ ├── static
│ ├── templates
│ └── testapi.py
├── run.py
└── venv
初始化檔案
import os
from flask import Flask
from flask_restful import Api, Resource
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
#app config, db, encryption, loginmanager
app = Flask(__name__)
app.config['SECRET_KEY'] =
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
#app API
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {"data": "Hello World"}
api.add_resource(HelloWorld,"/helloworld")
uj5u.com熱心網友回復:
我推薦這種結構(基于Flasky 應用程式的結構 - Miguel Grinberg):
├── app
│ ├── __init__.py
│ ├── models.py
│ ├── site.db
│ ├── static
│ ├── templates
│ ├── api
│ │ ├── __init__.py
│ │ └── hello_worlds.py
│ └── main
│ ├── __init__.py
│ ├── forms.py
│ └── routes.py (a.k.a. views.py)
├── tests
│ └── test_api.py
├── run.py
└── venv
api/hello_worlds.py
from flask_restful import Resource
class HelloWorld(Resource):
def get(self):
return {"data": "Hello World"}
api/__init__.py
from flask import Blueprint
from flask_restful import Api
from app.api.hello_worlds import HelloWorld
# Initialize the API component.
api_blueprint = Blueprint("api", __name__)
_api = Api(api_blueprint)
# Register the resources of the API to it.
_api.add_resource(HelloWorld, "/helloworld")
應用程式/__init__.py
import os
from flask import Flask
from flask_restful import Api, Resource
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
app = Flask(__name__)
app.config['SECRET_KEY'] =
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
from app.api import api_blueprint
app.register_blueprint(api_blueprint, url_prefix="/api/v1")
from app.main import main_blueprint
app.register_blueprint(main_blueprint)
http://localhost:5000/api/v1/helloworld要訪問您的資源,請向(例如)發出請求。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/443963.html
下一篇:攔截來自側邊欄面板的請求
