我有一个跨多个模块的大型Flask项目。我希望所有这些模块都能访问我的MongoDB (PyMongo)数据库连接。根据最佳实践,我希望精确地在整个应用程序(即所有模块)中保持一个连接池。
不可行的解决方案(来自其他相关的StackOverflow答案)
db对象不是只读的时候)。示例如下。Flask.g“全局”变量,因为它与每个请求一起被删除,使得它基本上等同于第2点。config.py),并在需要时从其他模块调用它,因为每当我从不同的模块调用它时,我都会创建新的连接。问题
示例
这是我如何创建全局变量并跨模块使用它的一个最起码的工作示例(在“不可行的解决方案”中的第1点)。
main.py
from module1 import helper_function
app = Flask(__name__)
db = new_db_connection()
@app.route('/page1'):
def page1():
db_return = db.query1()
db.cache = new_value # this makes this entire code thread-unsafe
return db_return
@app.route('/page2'):
def page2():
db_return = db.query2()
db_return2 = helper_function(db) # doesn't seem right that I have to pass this object around all the time
return db_return模1.py
def helper_function(db):
db_return = db.query3()
return db_return发布于 2020-01-01 18:23:31
我一直在同一条船上,我想出的答案是向每个函数传递一个参数。如果有更好的方法我很想知道。
实际上,我不是传递db值,而是传递一个自定义上下文对象,该对象具有mongoclient以及其他一些有用的方法(例如记录结果ids等)。
class Context:
def __init__(self, cs: str = None) -> None:
self.cs = cs
try:
self.db = pymongo.MongoClient(self.cs).get_database()
except Exception as e:
raise ValueError(f'Failed to connect to server using connection string {self.cs}')https://stackoverflow.com/questions/59515070
复制相似问题