将 Python Flask 应用程序拆分为多个文件 [英] Split Python Flask app into multiple files

查看:28
本文介绍了将 Python Flask 应用程序拆分为多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解如何将 Flask 应用拆分为多个文件.

I'm having trouble understanding how to split a flask app into multiple files.

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

I'm creating a web service and I want to split the api's into different files (AccountAPI.py, UploadAPI.py, ...), just so I don't have one huge python file.

我已经读到您可以使用蓝图执行此操作,但我不完全确定该路线是否适合我.

I've read that you can do this with Blueprints, but I'm not entirely sure that route is the right one for me.

最终我想运行一个 Main python 文件并包含其他文件,以便在运行时将它们视为一个大文件.

Ultimately I want to run one Main python file and include other files so that when it runs, they are considered one big file.

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

For example if I have Main.py and AccountAPI.py I want to be able to do this:

Main.py:

from flask import Flask
import AccountAPI

app = Flask(__name__)

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

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

AccountAPI.py:

AccountAPI.py:

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

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

I know with this example it obviously won't work, but is it possible to do something like that?

谢谢

推荐答案

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

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

主文件

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

AccountAPI.py

from flask import Blueprint

account_api = Blueprint('account_api', __name__)

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

如果这是一个选项,您可以考虑为不同的 API/蓝图使用不同的 URL 前缀,以便将它们干净地分开.这可以通过对上述 register_blueprint 调用稍作修改来完成:

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.

这篇关于将 Python Flask 应用程序拆分为多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆