1.. _pymongo-and-mod_wsgi:
2
3PyMongo and mod_wsgi
4====================
5
6To run your application under `mod_wsgi <http://code.google.com/p/modwsgi/>`_,
7follow these guidelines:
8
9* Run ``mod_wsgi`` in daemon mode with the ``WSGIDaemonProcess`` directive.
10* Assign each application to a separate daemon with ``WSGIProcessGroup``.
11* Use ``WSGIApplicationGroup %{GLOBAL}`` to ensure your application is running
12  in the daemon's main Python interpreter, not a sub interpreter.
13
14For example, this ``mod_wsgi`` configuration ensures an application runs in the
15main interpreter::
16
17    <VirtualHost *>
18        WSGIDaemonProcess my_process
19        WSGIScriptAlias /my_app /path/to/app.wsgi
20        WSGIProcessGroup my_process
21        WSGIApplicationGroup %{GLOBAL}
22    </VirtualHost>
23
24If you have multiple applications that use PyMongo, put each in a separate
25daemon, still in the global application group::
26
27    <VirtualHost *>
28        WSGIDaemonProcess my_process
29        WSGIScriptAlias /my_app /path/to/app.wsgi
30        <Location /my_app>
31            WSGIProcessGroup my_process
32        </Location>
33
34        WSGIDaemonProcess my_other_process
35        WSGIScriptAlias /my_other_app /path/to/other_app.wsgi
36        <Location /my_other_app>
37            WSGIProcessGroup my_other_process
38        </Location>
39
40        WSGIApplicationGroup %{GLOBAL}
41    </VirtualHost>
42
43Background: ``mod_wsgi`` can run in "embedded" mode when only WSGIScriptAlias
44is set, or "daemon" mode with WSGIDaemonProcess. In daemon mode, ``mod_wsgi``
45can run your application in the Python main interpreter, or in sub interpreters.
46The correct way to run a PyMongo application is in daemon mode, using the main
47interpreter.
48
49Python C extensions in general have issues running in multiple
50Python sub interpreters. These difficulties are explained in the documentation for
51`Py_NewInterpreter <http://docs.python.org/2/c-api/init.html#Py_NewInterpreter>`_
52and in the `Multiple Python Sub Interpreters
53<https://code.google.com/p/modwsgi/wiki/ApplicationIssues#Multiple_Python_Sub_Interpreters>`_
54section of the ``mod_wsgi`` documentation.
55
56Beginning with PyMongo 2.7, the C extension for BSON detects when it is running
57in a sub interpreter and activates a workaround, which adds a small cost to
58BSON decoding. To avoid this cost, use ``WSGIApplicationGroup %{GLOBAL}`` to
59ensure your application runs in the main interpreter.
60
61Since your program runs in the main interpreter it should not share its
62process with any other applications, lest they interfere with each other's
63state. Each application should have its own daemon process, as shown in the
64example above.
65