Flask 为什么在创建应用程序实例之前访问应用程序路由

Flask 为什么在创建应用程序实例之前访问应用程序路由,flask,Flask,我正在阅读一个Flask示例,该示例从单个脚本应用程序过渡到应用程序工厂,因此引入了蓝图。使用蓝图的理由是,应用程序实例现在是在运行时创建的,而不是存在于全局范围中(就像在单脚本应用程序中一样)。这会导致在调用create\u app()后存在app.route decorator,这本书指出这已经太晚了。为什么调用create\u app()后app.route decorator会被认为太晚了?为什么我们要在调用create_app()之前访问路由 编写应用程序工厂时,在调用工厂之前,没有应

我正在阅读一个Flask示例,该示例从单个脚本应用程序过渡到应用程序工厂,因此引入了蓝图。使用蓝图的理由是,应用程序实例现在是在运行时创建的,而不是存在于全局范围中(就像在单脚本应用程序中一样)。这会导致在调用
create\u app()
后存在app.route decorator,这本书指出这已经太晚了。为什么调用
create\u app()
后app.route decorator会被认为太晚了?为什么我们要在调用
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
#这将失败,应用程序不存在
@app.route(“/blog/”)
def post(id):
...
#这是因为路线已在蓝图上注册
#稍后将在应用程序上注册
blog\u bp=Blueprint('blog'、名称、url\u前缀='/blog')
@blog_bp.route(“/”)
def post(id):
...
def create_app():
app=烧瓶(名称)
...
应用程序注册蓝图(博客)
...
返回应用程序
#应用程序仍然不存在,它只在服务器使用工厂时存在