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

2024-04-26 07:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我正在创建一个web服务,我想将api拆分成不同的文件(AccountAPI.py、UploadAPI.py,…),这样我就没有一个巨大的python文件。

我听说你可以用蓝图来做,但我不完全确定那条路线是否适合我。

最终,我希望运行一个主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"

我知道用这个例子显然行不通,但有没有可能做这样的事情呢?

谢谢


Tags: 文件namepyimportapiwebapp应用程序
3条回答

是的,蓝图是正确的方法。你要做的事情可以这样实现:

主.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()

会计api.py

from flask import Blueprint

account_api = Blueprint('account_api', __name__)

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

如果这是一个选项,您可以考虑为不同的api/Blueprints使用不同的URL前缀,以便将它们完全分离。这可以通过稍微修改上面的register_blueprint调用来完成:

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

对于进一步的文档,您还可以查看the official docs

如果您正在使用蓝图,并且要在模板中路由/重定向到蓝图的url,则需要使用正确的url_for语句。

在您的情况下,如果要打开蓝图的url帐户,您必须在模板中这样声明:

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

而对于主应用程序,它将如下所示:

redirect(url_for('account_api.account'))

否则werkzeug库将抛出一个错误。

使用Blueprint可以在routes目录中添加路由。

结构

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

__初始py

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

from .index import *
from .users import *

指数py

from flask import render_template
from . import routes

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

用户.py

from flask import render_template
from . import routes

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

应用程序py

from routes import *
app.register_blueprint(routes)

如果你想添加一个新的路由文件,比如说accounts.py,你只需要在routes目录中创建文件accounts.py,就像index.pyusers.py,然后导入到routes.__init__.py文件中

from .accounts import *

相关问题 更多 >