如何将烧瓶应用程序分成多个py文件? [英] How to divide flask app into multiple py files?

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

问题描述

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


$ b $

  @ app.route('/ somepath')
def somehandhand():
#Handler code这里

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

解决方案

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



然而,


Flask使用蓝图的概念来制作应用程序组件,并支持应用程序中或应用程序中的通用模式。


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

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

然后在主要部分使用它:

<$从yourapplication.simple_page导入简单的p $ p> e_page
$ b $ app = Flask(__ name__)
app.register_blueprint(simple_page)

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


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

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?

解决方案

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

However,

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)

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

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

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