为什么在创建应用程序实例之前访问应用程序路线(Why access app routes prior to creating an app instance)

系统教程 行业动态 更新时间:2024-06-14 16:59:47
为什么在创建应用程序实例之前访问应用程序路线(Why access app routes prior to creating an app instance)

我正在阅读Flask示例,该示例从单个脚本应用程序转换到应用程序工厂,因此引入了蓝图。 使用蓝图的原因是因为应用程序实例现在是在运行时创建的,而不是在全局范围中存在(如在单个脚本应用程序中)。 这会导致app.route装饰器在调用create_app()后存在,本书指出这太晚了。 为什么在调用create_app()之后app.route装饰器存在为时已晚? 为什么我们要在调用create_app()之前访问路由?

I was reading up on a Flask example that transitions from a single script application to an application factory and for this reason blueprints are introduced. The reasoning for using blueprints is because the application instance is now created at runtime instead of existing in the global scope (as it was in the single script application). This causes the app.route decorator to exist after create_app() is invoked, which the book states is too late. Why is it considered too late for the app.route decorator to exist after create_app() is invoked? Why would we want to access the routes prior to invoking create_app()?

最满意答案

当您编写应用程序工厂时,在调用工厂之前您没有应用程序实例。 工厂只在运行服务器时调用,但在运行服务器之前需要定义路由。 因此,您将它们附加到蓝图上,并在工厂中的应用程序上注册蓝图。

# this would fail, app doesn't exist @app.route('/blog/<int:id>') def post(id): ... # this works because the route is registered on the blueprint # which is later registered on the app blog_bp = Blueprint('blog', __name__, url_prefix='/blog') @blog_bp.route('/<int:id>') def post(id): ... def create_app(): app = Flask(__name__) ... app.register_blueprint(blog_bp) ... return app # app still doesn't exist, it only exists when the server uses the factory

When you write an app factory, you don't have an app instance until the factory is called. The factory is only called when running the server, but you need to define your routes before you run the server. So you attach them to blueprints instead, and register the blueprints on the app in the factory.

# this would fail, app doesn't exist @app.route('/blog/<int:id>') def post(id): ... # this works because the route is registered on the blueprint # which is later registered on the app blog_bp = Blueprint('blog', __name__, url_prefix='/blog') @blog_bp.route('/<int:id>') def post(id): ... def create_app(): app = Flask(__name__) ... app.register_blueprint(blog_bp) ... return app # app still doesn't exist, it only exists when the server uses the factory

更多推荐

本文发布于:2023-04-17 09:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/8571eade34250185f1c0afd1c76d038a.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用程序   实例   路线   access   app

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!