You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask主应用与蓝图间传递MongoDB对象?

问题原因及解决方案

错误原因

  1. 蓝图模块级别直接访问current_app:蓝图文件在导入阶段(应用启动前)就执行了print(current_app.config)和db = current_app.config['db1'],此时没有激活的应用上下文,current_app无法绑定到当前应用,触发Working outside of application context错误。
  2. 数据库对象未存入应用配置:主应用中初始化的db1仅在临时上下文块内有效,且未存入app.config,即使上下文正常,蓝图也无法通过current_app.config获取该对象。

修正后的代码实现

主应用代码

from flask import Flask, render_template
import pymongo
from admin_component.bp1 import bp_1

def init_db1():
    try:
        mongo = pymongo.MongoClient(
            host='mongodb+srv://<username>:<passwrd>@cluster0.bslkwxdx.mongodb.net/?retryWrites=true&w=majority',
            serverSelectionTimeoutMS = 1000
        )
        db1 = mongo.test_db1.test_collection1
        mongo.server_info()  # 测试数据库连接有效性
        return db1
    except Exception as e:
        print(f'无法连接数据库!! 错误信息: {e}')
        return None

app = Flask(__name__)
# 初始化数据库并存入应用全局配置
app.config['db1'] = init_db1()
# 注册蓝图
app.register_blueprint(bp_1, url_prefix='/admin')

@app.route('/')
def test():
    return '<h1>This is a Test</h1>'

if __name__ == '__main__':
    app.run(port=10001, debug=True)

蓝图代码

from flask import Blueprint, current_app
from bson.objectid import ObjectId
import json

bp_1 = Blueprint('bp1', __name__, static_folder='static', template_folder='templates')

# 在视图函数内访问数据库(此时请求上下文已激活)
@bp_1.route('/check_db')
def check_db():
    db = current_app.config['db1']
    if not db:
        return '数据库连接失败'
    # 示例:获取集合内文档总数
    doc_count = db.count_documents({})
    return f'集合中文档总数: {doc_count}'

关键说明

  • 禁止模块级别访问current_app:只有在请求处理(视图函数执行)、CLI命令运行,或手动激活应用上下文时,current_app才有效。所有依赖current_app的操作必须放在这些上下文激活的场景中。
  • 多数据库扩展方案:如果需要添加更多数据库,只需复刻init_db1的初始化逻辑,将结果存入app.config的不同键名(如app.config['db2'] = init_db2()),蓝图即可按需通过current_app.config['db2']获取对应数据库对象。

内容的提问来源于stack exchange,提问作者d0ppL3G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:55:29