2
===========================
6
from pymongo import Connection, ReplicaSetConnection
8
PyMongo supports `Gevent <http://www.gevent.org/>`_. Primarily, this means that
9
:meth:`~pymongo.connection.Connection.start_request()` can ensure that the
10
current greenlet (not merely the current thread) uses the same socket for all
11
operations until :meth:`~pymongo.connection.Connection.end_request()` is called.
12
See the :doc:`requests documentation <requests>` for details on requests in
15
Using Gevent Without Threads
16
----------------------------
18
Typically when using Gevent, you will run ``from gevent import monkey;
19
monkey.patch_all()`` early in your program's execution. From then on, all
20
thread-related Python functions will act on `greenlets
21
<http://pypi.python.org/pypi/greenlet>`_ instead of threads, and PyMongo will
22
treat greenlets as if they were threads transparently. Each greenlet will use a
23
socket exclusively by default.
27
>>> from gevent import monkey; monkey.patch_all()
28
>>> connection = Connection()
30
Make sure you're using the latest version of Gevent to ensure that
31
thread-locals are patched to act like greenlet-locals.
33
Using Gevent With Threads
34
-------------------------
36
If you need to use standard Python threads in the same process as Gevent and
37
greenlets, you only need to run ``monkey.patch_socket()``, rather than
38
``monkey.patch_all()``, and create a
39
:class:`~pymongo.connection.Connection` with ``use_greenlets=True``.
40
The :class:`~pymongo.connection.Connection` will use a special greenlet-aware
41
connection pool that allocates a socket for each greenlet, ensuring consistent
46
>>> from gevent import monkey; monkey.patch_socket()
47
>>> connection = Connection(use_greenlets=True)
49
An instance of :class:`~pymongo.replica_set_connection.ReplicaSetConnection`
50
created with ``use_greenlets=True`` will also use a greenlet-aware pool.
51
Additionally, it will use a background greenlet instead of a background thread
52
to monitor the state of the replica set.
54
Using :meth:`~pymongo.replica_set_connection.ReplicaSetConnection.start_request()`
55
with :class:`~pymongo.ReadPreference` PRIMARY ensures that the current greenlet
56
uses the same socket for all operations until a call to :meth:`end_request()`.
58
You must `install Gevent <http://gevent.org/>`_ to use
59
:class:`~pymongo.replica_set_connection.ReplicaSetConnection`
60
with ``use_greenlets=True``
64
>>> from gevent import monkey; monkey.patch_socket()
65
>>> rsc = ReplicaSetConnection(
66
... 'mongodb://localhost:27017,localhost:27018,localhost:27019',
67
... replicaSet='repl0', use_greenlets=True)