将 Python Flask 应用程序拆分为多个文件

我很难理解如何将一个烧瓶应用程序分成多个文件。

我正在创建一个 Web 服务,我想把 API 分成不同的文件(AccountAPI.py,UploadAPI.py,...) ,这样我就不会有一个巨大的 python 文件了。

我知道你可以用蓝图做到这一点,但我不完全确定那条路线是否适合我。

最终,我想运行一个 Main python 文件并包含其他文件,这样当它运行时,它们就被认为是一个大文件。

例如,如果我有 Main.py 和 AccountAPI.py,我希望能够这样做:

Py:

from flask import Flask
import AccountAPI


app = Flask(__name__)


@app.route("/")
def hello():
return "Hello World!"


if __name__ == "__main__":
app.run()

帐户 API.py:

@app.route("/account")
def accountList():
return "list of accounts"

我知道这个例子显然不会起作用,但是有可能做这样的事情吗?

谢谢

52478 次浏览

Yes, Blueprints are the right way to do it. What you are trying to do can be achieved like this:

Main.py

from flask import Flask
from AccountAPI import account_api


app = Flask(__name__)


app.register_blueprint(account_api)


@app.route("/")
def hello():
return "Hello World!"


if __name__ == "__main__":
app.run()

AccountAPI.py

from flask import Blueprint


account_api = Blueprint('account_api', __name__)


@account_api.route("/account")
def accountList():
return "list of accounts"

If this is an option, you might consider using different URL prefixes for the different APIs/Blueprints in order to cleanly separate them. This can be done with a slight modification to the above register_blueprint call:

app.register_blueprint(account_api, url_prefix='/accounts')

For further documentation, you may also have a look at the official docs.

One another way to do this can be with lazy loading, where you would explicitly attach view functions on need basis.

If you are using blueprints and want to route / redirect to a url of your blueprint inside a template you are using you need to use the correct url_for statement.

In your case if you would like to open the url account of your blueprint you have to state it like this in your template:

href="\{\{ url_for('account_api.account') }}"

and for the main app it would look like this:

redirect(url_for('account_api.account'))

Otherwise the werkzeug library will throw an error.

Using Blueprint you can add your routes in the routes directory.

Structure

app.py
routes
__init__.py
index.py
users.py

__init__.py

from flask import Blueprint
routes = Blueprint('routes', __name__)


from .index import *
from .users import *

index.py

from flask import render_template
from . import routes


@routes.route('/')
def index():
return render_template('index.html')

users.py

from flask import render_template
from . import routes


@routes.route('/users')
def users():
return render_template('users.html')

app.py

from routes import *
app.register_blueprint(routes)

If you want to add a new route file, say accounts.py, you just need to create the file accounts.py in the routes directory, just like index.py and users.py, then import it in the routes.__init__.py file

from .accounts import *