Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create pymongo connection per request in Flask

In my Flask application, I hope to use pymongo directly. But I am not sure what's the best way to create pymongo connection for each request and how to reclaim the connection resource.

I know Connection in pymongo is thread-safe and has built-in pooling. I guess I need to create a global Connection instance, and use before_request to put it in flask g.

In the 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'):
        # FIX
        pass

In admin/views.py:

from flask import g
@admin.route('/')
def index():
    # do something with g.db

It actually works. So questions are:

  1. Is this the best way to use Connection in flask?

  2. Do I need to explicitly reclaim resources in teardown_request and how to do it?

like image 692
maple Avatar asked Jul 08 '12 05:07

maple


2 Answers

I still think this is an interesting question, but why no response... So here is my update.

For the first question, I think using current_app is more clearer in Flask.

In app.py

app = Flask(__name__)
connection = Connection()
db = connection['test']
app.db = db

In the view.py

from Flask import current_app
db = current_app.db
# do anything with db

And by using current_app, you can use application factory to create more than one app as http://flask.pocoo.org/docs/patterns/appfactories/

And for the second question, I'm still figuring it out.

like image 107
maple Avatar answered Oct 06 '22 03:10

maple


Here's example of using flask-pymnongo extension:

Example:

your mongodb uri (till db name) in app.config like below

app.config['MONGO_URI'] = 'mongodb://192.168.1.1:27017/your_db_name'
mongo = PyMongo(app, config_prefix='MONGO')

and then under your api method where u need db do the following:

db = mongo.db

Now you can work on this db connection and get your data:

users_count = db.users.count()
like image 35
Snehal Parmar Avatar answered Oct 06 '22 02:10

Snehal Parmar