使用蓝图中的配置连接到数据库时 Flask App 中的 AssertionError

AssertionError in Flask App when connecting to database using config in blueprint

我正在构建一个连接到现有 MySQL 数据库的 Flask 应用程序,作为学习 Flask 的练习。我在尝试从从蓝图实例化的数据库对象连接到数据库时遇到错误。

我的项目结构如下

项目
├────实例
├──── config.py
├──── 申请
├──── _src
├──── db.py
├──── extensions.py
├──── admin
├──── 模板
├──── __init__.py
├──── views.py
├──── 静态
__init__.py

我的__init__.py(在应用程序目录中)有以下代码:

from flask import Flask

# Config file
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("config.py")

# Blueprints
from application.admin.views import adminBlueprint

# Register the blueprint
app.register_blueprint(adminBlueprint)

我的配置文件有以下内容:

#####################
# Database details ##
#####################
DB_USERNAME = "username"
DB_PASSWORD = "password"
DB_DATABASE_NAME = "databasename"
DB_HOST = "localhost"

我的管理文件夹中的视图文件具有以下内容:

# Imports
from flask import render_template, Blueprint
from .._src.db import DB
from .._src import admin as admin

# Config
adminBlueprint = Blueprint("admin", __name__, template_folder="templates")

# Routes
@adminBlueprint.route("/admin")
def admin():
    # Connect to the database
    db = DB()
    cursor, conn = db.connectDB()
    # Get the required data
    projects = admin.getProjects(cursor, "all")
    # Close the database connection
    db.close()
    # Render data to the template
    return render_template("admin.html", projects=projects)

我的扩展文件,位于 _src 文件夹中,用于允许从蓝图访问 MySQL 对象,具有以下代码:

from flaskext.mysql import MySQL
mysql = MySQL()

而我的 _src 目录中的 db 文件具有以下内容:

from flask import current_app
from .._src.extensions import mysql

class DB:
    def __init__(self):
        # Something will be done here in the future
        pass

    def connectDB(self):
        # Provide the database connection details
        current_app.config['MYSQL_DATABASE_USER'] = current_app.config["DB_USERNAME"]
        current_app.config['MYSQL_DATABASE_PASSWORD'] = current_app.config["DB_PASSWORD"]
        current_app.config['MYSQL_DATABASE_DB'] = current_app.config["DB_DATABASE_NAME"]
        current_app.config['MYSQL_DATABASE_HOST'] = current_app.config["DB_HOST"]
        mysql.init_app(current_app)
        # Connect to the database
        try:
            self.conn = mysql.connect()
            cursor = self.conn.cursor()
            # Return the cursor object
            return cursor, self.conn
        except:
            return False

    def close(self):
        self.conn.close()

我收到以下错误:

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.

并且调试器指向数据库文件中的这个文件:

mysql.init_app(current_app)

我有点不知所云,我不太明白问题出在哪里。我只能从初始化 Flask 应用程序的相同位置初始化 MySQL 对象吗?如果是这样,我如何才能从蓝图中访问 MySQL 对象?

感谢任何帮助。

我能够通过将我的应用程序实例化到我的扩展文件而不是我的初始化文件来解决这个问题:

extensions.py

from flask import Flask
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile("config.py")

然后,在我的数据库连接对象中,我可以导入当前应用程序以获取设置:

from flask import current_app
from .._src.extensions import mysql

我也删除了这一行,因为我现在在我的扩展文件中实现了这一点:

mysql.init_app(current_app)