Reputation: 14065
Is it better to do
from pymongo import Connection
conn = Connection()
db = conn.db_name
def contrivedExample(firstName)
global db
return db.people.find_one({'first-name': firstName})
or
from pymongo import Connection
def contrivedExample(firstName):
with Connection() as conn:
return conn.db_name.people.find_one({'first-name': firstName})
Various basic MongoDB tutorials (Python-oriented or not) imply that an app should connect once at startup; is that actually the case? Does the answer change for non-trivial, long-running applications? Does the answer change for web applications specifically? What are the pros/cons of going single-connection vs. connection-per-request?
Assuming "once at startup" is the right answer, would it be appropriate to start that connection in __init__.py
?
Upvotes: 5
Views: 4193
Reputation: 6922
The pymongo Connection class supports connection pooling and, as of version 2.2, the auto_start_request
option ensures that the same socket will be used for a connection activity during the lifetime of the thread (default behavior). Additionally, there is built-in support for reconnecting when necessary, although your application code should handle the immediate exception.
To your question, I believe it'd be preferable to rely on pymongo's own connection pooling and request a new connection per thread. This Stack Overflow thread also discusses some best practices and explains some of the options at play, which you may find helpful. If necessary, you have the option of sharing the same socket between threads.
Upvotes: 4