Managing a MongoDB Connection in Python

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 MongoDB basic tutorials (whether Python-oriented or not) imply that the application must connect once at startup; is this really the case? Does the response to non-trivial long-term applications change? Is the answer modified for web applications? What are the advantages / disadvantages of switching to a single connection or connection per request?

Assuming that โ€œonce at startupโ€ is the correct answer, would it be wise to run this connection in __init__.py ?

+4
source share
1 answer

The pymongo Connection class supports connection pooling and, starting with version 2.2, the auto_start_request parameter ensures that the same socket will be used for connection activity during the flow life cycle (default behavior). In addition, there is built-in support for reconnecting when necessary, although your application code should handle an immediate exception.

To your question, I believe that it would be preferable to rely on your own pymongo connection pool and request a new connection to the stream. This thread also discusses some recommendations and explains some of the game options that you might find useful. If necessary, you have the option of sharing the same socket between threads.

+3
source

Source: https://habr.com/ru/post/1439440/


All Articles