Python Flask 框架。AssertionError:处理第一个请求后调用了设置函数

Sha*_*rdj 4 python flask

我一直在按照 Flask 教程添加数据库,在他们的示例中,他们使用 mysqlite,而我使用 MySQL,但我认为这不会产生巨大的差异。https://flask.palletsprojects.com/en/1.1.x/tutorial/database/

这是我尝试使用的 mysql 库https://flask-mysql.readthedocs.io/en/stable/

然而,无论我做什么,我似乎都无法摆脱这个断言错误:

AssertionError: A setup function was called after the first request was handled.  This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.
Run Code Online (Sandbox Code Playgroud)

该错误仅在尝试使用 /dbtest 路径时发生。

这是我的最小 __init__.py

import os

from flask import Flask, render_template
from . import db


def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        MYSQL_DATABASE_HOST='mysql-svc',
        MYSQL_DATABASE_USER='root',
        MYSQL_DATABASE_PASSWORD='root',
        DEBUG=True,
        TESTING=True
    )

    db.init_app(app)

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    @app.route('/dbtest')
    def db_test():
        with app.app_context():
            cursor = db.get_cursor()
            cursor.execute('SHOW DATABASES')
            return cursor.fetchall()

    return app
Run Code Online (Sandbox Code Playgroud)

这是位于同一目录中的 db.py

from flaskext.mysql import MySQL
from flask import current_app, g


def get_cursor():
    if 'db_cursor' not in g:
        mysql = MySQL()
        mysql.init_app(current_app)
        g.db_cursor = mysql.get_db().cursor()
    return g.db_cursor


def close_db(e=None):
    db = g.pop('db_cursor', None)

    if db is not None:
        db.close()


def init_app(app):
    app.teardown_appcontext(close_db)
Run Code Online (Sandbox Code Playgroud)

我读到的有关此错误的所有内容似乎都表明,在尝试访问数据库或其他内容后,我在某种程度上搞乱了路由?但我只是按照教程了解如何设置路由。我可能在这里遗漏了一些明显的东西,我相信这是现在的问题mysql.init_app,但我仍然不知道如何做到这一点。

小智 9

这个问题可能是相关的DEBUG = True,如果我自己刚刚遇到这个问题来到这里寻找解决方案。下面已关闭的 github 票证中有一条评论,表明这在某个时候是一个问题。截至今天,这似乎仍然是一个问题。 https://github.com/ga4gh/ga4gh-server/issues/791