如何将flask app分成多个py文件? [英] How to divide flask app into multiple py files?

查看:26
本文介绍了如何将flask app分成多个py文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Flask 应用程序目前由一个带有多个路由的 test.py 文件和定义的 main() 路由组成.有什么方法可以创建一个 test2.py 文件,其中包含 test.py 中未处理的路由?

My flask application currently consists of a single test.py file with multiple routes and the main() route defined. Is there some way I could create a test2.py file that contains routes that were not handled in test.py?

@app.route('/somepath')
def somehandler():
    # Handler code here

我担心 test.py 中的路由太多,并希望使它可以运行 python test.py,它也会选择test.py 上的路由就好像它是同一个文件的一部分一样.我必须在 test.py 和/或包含在 test2.py 中进行哪些更改才能使其正常工作?

I am concerned that there are too many routes in test.py and would like to make it such that I can run python test.py, which will also pick up the routes on test.py as if it were part of the same file. What changes to I have to make in test.py and/or include in test2.py to get this to work?

推荐答案

您可以使用通常的 Python 包结构将您的 App 分成多个模块,查看 Flask 文档.

You can use the usual Python package structure to divide your App into multiple modules, see the Flask docs.

然而,

Flask 使用蓝图的概念来制作应用程序组件并支持应用程序内或跨应用程序的通用模式.

Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications.

您可以在单独的文件中创建应用程序的子组件作为蓝图:

You can create a sub-component of your app as a Blueprint in a separate file:

simple_page = Blueprint('simple_page', __name__, template_folder='templates')
@simple_page.route('/<page>')
def show(page):
    # stuff

然后在主体部分使用它:

And then use it in the main part:

from yourapplication.simple_page import simple_page

app = Flask(__name__)
app.register_blueprint(simple_page)

蓝图还可以捆绑特定资源:模板或静态文件.有关所有详细信息,请参阅 Flask 文档.

Blueprints can also bundle specific resources: templates or static files. Please refer to the Flask docs for all the details.

这篇关于如何将flask app分成多个py文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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