Gevent

PyMongo supports Gevent. Simply call Gevent’smonkey.patch_all() before loading any other modules:

  1. >>> # You must call patch_all() *before* importing any other modules
  2. >>> from gevent import monkey
  3. >>> _ = monkey.patch_all()
  4. >>> from pymongo import MongoClient
  5. >>> client = MongoClient()

PyMongo uses thread and socket functions from the Python standard library.Gevent’s monkey-patching replaces those standard functions so that PyMongodoes asynchronous I/O with non-blocking sockets, and schedules operationson 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 monkey.patch_all() whenyour application first begins, PyMongo automatically uses greenlets insteadof threads.

When shutting down, if your application calls join() onGevent’s Hub without first terminating these backgroundgreenlets, the call to join() blocks indefinitely. Youtherefore must close or dereference any activeMongoClient before exiting.

An example solution to this issue in some application frameworks is a signalhandler to end background greenlets when your application receives SIGHUP:

  1. import signal
  2.  
  3. def graceful_reload(signum, traceback):
  4. """Explicitly close some global MongoClient object."""
  5. client.close()
  6.  
  7. 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 -gevent-wait-for-hub option.See the uWSGI changelog for details.