我目前正在开发一个Flask项目,该项目使用多个蓝图和mongo进行数据存储。我创建了多个PyMongo实例以访问不同的数据库:
在app.py(这是项目的核心文件)中,我定义了实例:
# The PyMongo instance 'mongo_app' takes its uri from the project's config.
mongo_app.init_app(app)
# The second PyMongo instance is initialized with the needed uri.
mongo_project.init_app(app, uri="mongodb://mongodb:27017/rick_and_morty")
在项目的蓝图中,我需要使用其初始化了PyMongo对象'mongo_project'的数据库的名称,即'rick_and_morty'。
我的问题是,如何从PyMongo对象中吸收此信息?我正在尝试实现以下目标:
database_name = mongo_project.db_name #rick_and_morty
答案 0 :(得分:1)
将它们附加到Flask应用并使用current_app访问
# app.py
from collections import namedtuple
from flask import Flask
from my_blueprint import app_blueprint
app = Flask(__name__)
app.mongo_project = namedtuple("whatever", ["db_name"])(db_name="db_name_1")
app.register_blueprint(app_blueprint)
# my_blueprint.py
from flask import Blueprint, current_app
app_blueprint = Blueprint('app_blueprint', __name__)
@app_blueprint.route("/blueprint_route")
def foobar():
database_name = current_app.mongo_project.db_name
return database_name
答案 1 :(得分:1)
您还可以使用pymongo中的 uri_parser :http://api.mongodb.com/python/current/api/pymongo/uri_parser.html
Python 2.7.13 (default, Jun 9 2017, 18:24:27)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> parsed=pymongo.uri_parser.parse_uri('mongodb://mongodb:27017/rick_and_morty')
>>> print parsed['database']
rick_and_morty