如何使用 mongoengine 只打开一个到 mongodb 的连接?
How open just one connection to mongodb with mongoengine?
目前我有一个超级简单的函数来打开与mongodb的连接:
from mongoengine import connect
connection = connect('<MY_DATABASE>')
我在所有需要与数据库进行交易的文件中导入连接变量。但是,对于每个文件,都会打开一个到数据库的新连接,我只想在整个应用程序中使用 1 个。
问题在于它在每个需要访问数据库的文件中导入并调用了配置 class。什么时候应该只导入到应用程序的组合根中。
像这样:
from sanic import Sanic
from sanic.response import json
from routes.user_routes import user_router
from models.config import Config
Config.start_connection()
app = Sanic('TodoServer')
app.blueprint(user_router)
@app.route('/')
async def check_health(request):
return json({ 'status': True, 'message': 'Server is up' });
if __name__ == '__main__':
app.run(host='127.0.0.1', port=3000, debug=True);
目前我有一个超级简单的函数来打开与mongodb的连接:
from mongoengine import connect
connection = connect('<MY_DATABASE>')
我在所有需要与数据库进行交易的文件中导入连接变量。但是,对于每个文件,都会打开一个到数据库的新连接,我只想在整个应用程序中使用 1 个。
问题在于它在每个需要访问数据库的文件中导入并调用了配置 class。什么时候应该只导入到应用程序的组合根中。
像这样:
from sanic import Sanic
from sanic.response import json
from routes.user_routes import user_router
from models.config import Config
Config.start_connection()
app = Sanic('TodoServer')
app.blueprint(user_router)
@app.route('/')
async def check_health(request):
return json({ 'status': True, 'message': 'Server is up' });
if __name__ == '__main__':
app.run(host='127.0.0.1', port=3000, debug=True);