PyMongo supports Gevent. Simply call Gevent’s
monkey.patch_all() before loading any other modules:
>>> # You must call patch_all() *before* importing any other modules >>> from gevent import monkey >>> _ = monkey.patch_all() >>> from pymongo import MongoClient >>> client = MongoClient()
PyMongo uses thread and socket functions from the Python standard library. Gevent’s monkey-patching replaces those standard functions so that PyMongo does asynchronous I/O with non-blocking sockets, and schedules operations on greenlets instead of threads.
Avoid blocking in Hub.join¶
By default, PyMongo uses threads to discover and monitor your servers’ topology
(see Health Monitoring). If you execute
your application first begins, PyMongo automatically uses greenlets instead
When shutting down, if your application calls
Hub without first terminating these background
greenlets, the call to
join() blocks indefinitely. You
therefore must close or dereference any active
MongoClient before exiting.
An example solution to this issue in some application frameworks is a signal handler to end background greenlets when your application receives SIGHUP:
import signal def graceful_reload(signum, traceback): """Explicitly close some global MongoClient object.""" client.close() signal.signal(signal.SIGHUP, graceful_reload)
Applications using uWSGI prior to 1.9.16 are affected by this issue,
or newer uWSGI versions with the
See the uWSGI changelog for details.