In my Flask application, I hope to use pymongo directly. But I'm not sure what is the best way to create a pymongo connection for each request and how to restore the connection resource.
I know that the connection in pymongo is thread safe and has a built-in pool. I think I need to create a global instance of Connection and use before_request to put it in the g bulb.
In app.py:
from pymongo import Connection from admin.views import admin connection = Connection() db = connection['test'] @app.before_request def before_request(): g.db = db @app.teardown_request def teardown_request(exception): if hasattr(g, 'db'):
In admin / views.py:
from flask import g @admin.route('/') def index():
It really works. Therefore, the questions:
source share