modpython.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. .. _howto-deployment-modpython:
  2. ============================================
  3. How to use Django with Apache and mod_python
  4. ============================================
  5. .. highlight:: apache
  6. Apache_ with `mod_python`_ currently is the preferred setup for using Django
  7. on a production server.
  8. mod_python is similar to (and inspired by) `mod_perl`_ : It embeds Python within
  9. Apache and loads Python code into memory when the server starts. Code stays in
  10. memory throughout the life of an Apache process, which leads to significant
  11. performance gains over other server arrangements.
  12. Django requires Apache 2.x and mod_python 3.x, and you should use Apache's
  13. `prefork MPM`_, as opposed to the `worker MPM`_.
  14. .. seealso::
  15. * Apache is a big, complex animal, and this document only scratches the
  16. surface of what Apache can do. If you need more advanced information about
  17. Apache, there's no better source than `Apache's own official
  18. documentation`_
  19. * You may also be interested in :ref:`How to use Django with FastCGI, SCGI,
  20. or AJP <howto-deployment-fastcgi>`.
  21. .. _Apache: http://httpd.apache.org/
  22. .. _mod_python: http://www.modpython.org/
  23. .. _mod_perl: http://perl.apache.org/
  24. .. _prefork MPM: http://httpd.apache.org/docs/2.2/mod/prefork.html
  25. .. _worker MPM: http://httpd.apache.org/docs/2.2/mod/worker.html
  26. .. _apache's own official documentation: http://httpd.apache.org/docs/
  27. Basic configuration
  28. ===================
  29. To configure Django with mod_python, first make sure you have Apache installed,
  30. with the mod_python module activated.
  31. Then edit your ``httpd.conf`` file and add the following::
  32. <Location "/mysite/">
  33. SetHandler python-program
  34. PythonHandler django.core.handlers.modpython
  35. SetEnv DJANGO_SETTINGS_MODULE mysite.settings
  36. PythonOption django.root /mysite
  37. PythonDebug On
  38. </Location>
  39. ...and replace ``mysite.settings`` with the Python import path to your Django
  40. project's settings file.
  41. This tells Apache: "Use mod_python for any URL at or under '/mysite/', using the
  42. Django mod_python handler." It passes the value of :ref:`DJANGO_SETTINGS_MODULE
  43. <django-settings-module>` so mod_python knows which settings to use.
  44. .. versionadded:: 1.0
  45. The ``PythonOption django.root ...`` is new in this version.
  46. Because mod_python does not know we are serving this site from underneath the
  47. ``/mysite/`` prefix, this value needs to be passed through to the mod_python
  48. handler in Django, via the ``PythonOption django.root ...`` line. The value set
  49. on that line (the last item) should match the string given in the ``<Location
  50. ...>`` directive. The effect of this is that Django will automatically strip the
  51. ``/mysite`` string from the front of any URLs before matching them against your
  52. URLconf patterns. If you later move your site to live under ``/mysite2``, you
  53. will not have to change anything except the ``django.root`` option in the config
  54. file.
  55. When using ``django.root`` you should make sure that what's left, after the
  56. prefix has been removed, begins with a slash. Your URLconf patterns that are
  57. expecting an initial slash will then work correctly. In the above example,
  58. since we want to send things like ``/mysite/admin/`` to ``/admin/``, we need
  59. to remove the string ``/mysite`` from the beginning, so that is the
  60. ``django.root`` value. It would be an error to use ``/mysite/`` (with a
  61. trailing slash) in this case.
  62. Note that we're using the ``<Location>`` directive, not the ``<Directory>``
  63. directive. The latter is used for pointing at places on your filesystem,
  64. whereas ``<Location>`` points at places in the URL structure of a Web site.
  65. ``<Directory>`` would be meaningless here.
  66. Also, if your Django project is not on the default ``PYTHONPATH`` for your
  67. computer, you'll have to tell mod_python where your project can be found:
  68. .. parsed-literal::
  69. <Location "/mysite/">
  70. SetHandler python-program
  71. PythonHandler django.core.handlers.modpython
  72. SetEnv DJANGO_SETTINGS_MODULE mysite.settings
  73. PythonOption django.root /mysite
  74. PythonDebug On
  75. **PythonPath "['/path/to/project'] + sys.path"**
  76. </Location>
  77. The value you use for ``PythonPath`` should include the parent directories of
  78. all the modules you are going to import in your application. It should also
  79. include the parent directory of the :ref:`DJANGO_SETTINGS_MODULE
  80. <django-settings-module>` location. This is exactly the same situation as
  81. setting the Python path for interactive usage. Whenever you try to import
  82. something, Python will run through all the directories in ``sys.path`` in turn,
  83. from first to last, and try to import from each directory until one succeeds.
  84. Make sure that your Python source files' permissions are set such that the
  85. Apache user (usually named ``apache`` or ``httpd`` on most systems) will have
  86. read access to the files.
  87. An example might make this clearer. Suppose you have some applications under
  88. ``/usr/local/django-apps/`` (for example, ``/usr/local/django-apps/weblog/`` and
  89. so forth), your settings file is at ``/var/www/mysite/settings.py`` and you have
  90. specified :ref:`DJANGO_SETTINGS_MODULE <django-settings-module>` as in the above
  91. example. In this case, you would need to write your ``PythonPath`` directive
  92. as::
  93. PythonPath "['/usr/local/django-apps/', '/var/www'] + sys.path"
  94. With this path, ``import weblog`` and ``import mysite.settings`` will both
  95. work. If you had ``import blogroll`` in your code somewhere and ``blogroll``
  96. lived under the ``weblog/`` directory, you would *also* need to add
  97. ``/usr/local/django-apps/weblog/`` to your ``PythonPath``. Remember: the
  98. **parent directories** of anything you import directly must be on the Python
  99. path.
  100. .. note::
  101. If you're using Windows, we still recommended that you use forward
  102. slashes in the pathnames, even though Windows normally uses the backslash
  103. character as its native separator. Apache knows how to convert from the
  104. forward slash format to the native format, so this approach is portable and
  105. easier to read. (It avoids tricky problems with having to double-escape
  106. backslashes.)
  107. This is valid even on a Windows system::
  108. PythonPath "['c:/path/to/project'] + sys.path"
  109. You can also add directives such as ``PythonAutoReload Off`` for performance.
  110. See the `mod_python documentation`_ for a full list of options.
  111. Note that you should set ``PythonDebug Off`` on a production server. If you
  112. leave ``PythonDebug On``, your users would see ugly (and revealing) Python
  113. tracebacks if something goes wrong within mod_python.
  114. Restart Apache, and any request to ``/mysite/`` or below will be served by
  115. Django. Note that Django's URLconfs won't trim the "/mysite/" -- they get passed
  116. the full URL.
  117. When deploying Django sites on mod_python, you'll need to restart Apache each
  118. time you make changes to your Python code.
  119. Multiple Django installations on the same Apache
  120. ================================================
  121. It's entirely possible to run multiple Django installations on the same Apache
  122. instance. Just use ``VirtualHost`` for that, like so::
  123. NameVirtualHost *
  124. <VirtualHost *>
  125. ServerName www.example.com
  126. # ...
  127. SetEnv DJANGO_SETTINGS_MODULE mysite.settings
  128. </VirtualHost>
  129. <VirtualHost *>
  130. ServerName www2.example.com
  131. # ...
  132. SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
  133. </VirtualHost>
  134. If you need to put two Django installations within the same ``VirtualHost``
  135. (or in different ``VirtualHost`` blocks that share the same server name),
  136. you'll need to take a special precaution to ensure mod_python's cache doesn't
  137. mess things up. Use the ``PythonInterpreter`` directive to give different
  138. ``<Location>`` directives separate interpreters::
  139. <VirtualHost *>
  140. ServerName www.example.com
  141. # ...
  142. <Location "/something">
  143. SetEnv DJANGO_SETTINGS_MODULE mysite.settings
  144. PythonInterpreter mysite
  145. </Location>
  146. <Location "/otherthing">
  147. SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
  148. PythonInterpreter othersite
  149. </Location>
  150. </VirtualHost>
  151. The values of ``PythonInterpreter`` don't really matter, as long as they're
  152. different between the two ``Location`` blocks.
  153. Running a development server with mod_python
  154. ============================================
  155. If you use mod_python for your development server, you can avoid the hassle of
  156. having to restart the server each time you make code changes. Just set
  157. ``MaxRequestsPerChild 1`` in your ``httpd.conf`` file to force Apache to reload
  158. everything for each request. But don't do that on a production server, or we'll
  159. revoke your Django privileges.
  160. If you're the type of programmer who debugs using scattered ``print``
  161. statements, note that ``print`` statements have no effect in mod_python; they
  162. don't appear in the Apache log, as one might expect. If you have the need to
  163. print debugging information in a mod_python setup, either do this::
  164. assert False, the_value_i_want_to_see
  165. Or add the debugging information to the template of your page.
  166. .. _mod_python documentation: http://modpython.org/live/current/doc-html/directives.html
  167. .. _serving-media-files:
  168. Serving media files
  169. ===================
  170. Django doesn't serve media files itself; it leaves that job to whichever Web
  171. server you choose.
  172. We recommend using a separate Web server -- i.e., one that's not also running
  173. Django -- for serving media. Here are some good choices:
  174. * lighttpd_
  175. * Nginx_
  176. * TUX_
  177. * A stripped-down version of Apache_
  178. * Cherokee_
  179. If, however, you have no option but to serve media files on the same Apache
  180. ``VirtualHost`` as Django, here's how you can turn off mod_python for a
  181. particular part of the site::
  182. <Location "/media">
  183. SetHandler None
  184. </Location>
  185. Just change ``Location`` to the root URL of your media files. You can also use
  186. ``<LocationMatch>`` to match a regular expression.
  187. This example sets up Django at the site root but explicitly disables Django for
  188. the ``media`` subdirectory and any URL that ends with ``.jpg``, ``.gif`` or
  189. ``.png``::
  190. <Location "/">
  191. SetHandler python-program
  192. PythonHandler django.core.handlers.modpython
  193. SetEnv DJANGO_SETTINGS_MODULE mysite.settings
  194. </Location>
  195. <Location "/media">
  196. SetHandler None
  197. </Location>
  198. <LocationMatch "\.(jpg|gif|png)$">
  199. SetHandler None
  200. </LocationMatch>
  201. .. _lighttpd: http://www.lighttpd.net/
  202. .. _Nginx: http://wiki.codemongers.com/Main
  203. .. _TUX: http://en.wikipedia.org/wiki/TUX_web_server
  204. .. _Apache: http://httpd.apache.org/
  205. .. _Cherokee: http://www.cherokee-project.com/
  206. .. _howto-deployment-modpython-serving-the-admin-files:
  207. .. _serving-the-admin-files:
  208. Serving the admin files
  209. =======================
  210. Note that the Django development server automagically serves admin media files,
  211. but this is not the case when you use any other server arrangement. You're
  212. responsible for setting up Apache, or whichever media server you're using, to
  213. serve the admin files.
  214. The admin files live in (:file:`django/contrib/admin/media`) of the Django
  215. distribution.
  216. Here are two recommended approaches:
  217. 1. Create a symbolic link to the admin media files from within your
  218. document root. This way, all of your Django-related files -- code **and**
  219. templates -- stay in one place, and you'll still be able to ``svn
  220. update`` your code to get the latest admin templates, if they change.
  221. 2. Or, copy the admin media files so that they live within your Apache
  222. document root.
  223. Using "eggs" with mod_python
  224. ============================
  225. If you installed Django from a Python egg_ or are using eggs in your Django
  226. project, some extra configuration is required. Create an extra file in your
  227. project (or somewhere else) that contains something like the following:
  228. .. code-block:: python
  229. import os
  230. os.environ['PYTHON_EGG_CACHE'] = '/some/directory'
  231. Here, ``/some/directory`` is a directory that the Apache webserver process can
  232. write to. It will be used as the location for any unpacking of code the eggs
  233. need to do.
  234. Then you have to tell mod_python to import this file before doing anything
  235. else. This is done using the PythonImport_ directive to mod_python. You need
  236. to ensure that you have specified the ``PythonInterpreter`` directive to
  237. mod_python as described above__ (you need to do this even if you aren't
  238. serving multiple installations in this case). Then add the ``PythonImport``
  239. line in the main server configuration (i.e., outside the ``Location`` or
  240. ``VirtualHost`` sections). For example::
  241. PythonInterpreter my_django
  242. PythonImport /path/to/my/project/file.py my_django
  243. Note that you can use an absolute path here (or a normal dotted import path),
  244. as described in the `mod_python manual`_. We use an absolute path in the
  245. above example because if any Python path modifications are required to access
  246. your project, they will not have been done at the time the ``PythonImport``
  247. line is processed.
  248. .. _Egg: http://peak.telecommunity.com/DevCenter/PythonEggs
  249. .. _PythonImport: http://www.modpython.org/live/current/doc-html/dir-other-pimp.html
  250. .. _mod_python manual: PythonImport_
  251. __ `Multiple Django installations on the same Apache`_
  252. Error handling
  253. ==============
  254. When you use Apache/mod_python, errors will be caught by Django -- in other
  255. words, they won't propagate to the Apache level and won't appear in the Apache
  256. ``error_log``.
  257. The exception for this is if something is really wonky in your Django setup. In
  258. that case, you'll see an "Internal Server Error" page in your browser and the
  259. full Python traceback in your Apache ``error_log`` file. The ``error_log``
  260. traceback is spread over multiple lines. (Yes, this is ugly and rather hard to
  261. read, but it's how mod_python does things.)
  262. If you get a segmentation fault
  263. ===============================
  264. If Apache causes a segmentation fault, there are two probable causes, neither
  265. of which has to do with Django itself.
  266. 1. It may be because your Python code is importing the "pyexpat" module,
  267. which may conflict with the version embedded in Apache. For full
  268. information, see `Expat Causing Apache Crash`_.
  269. 2. It may be because you're running mod_python and mod_php in the same
  270. Apache instance, with MySQL as your database backend. In some cases,
  271. this causes a known mod_python issue due to version conflicts in PHP and
  272. the Python MySQL backend. There's full information in the
  273. `mod_python FAQ entry`_.
  274. If you continue to have problems setting up mod_python, a good thing to do is
  275. get a barebones mod_python site working, without the Django framework. This is
  276. an easy way to isolate mod_python-specific problems. `Getting mod_python Working`_
  277. details this procedure.
  278. The next step should be to edit your test code and add an import of any
  279. Django-specific code you're using -- your views, your models, your URLconf,
  280. your RSS configuration, etc. Put these imports in your test handler function
  281. and access your test URL in a browser. If this causes a crash, you've confirmed
  282. it's the importing of Django code that causes the problem. Gradually reduce the
  283. set of imports until it stops crashing, so as to find the specific module that
  284. causes the problem. Drop down further into modules and look into their imports,
  285. as necessary.
  286. .. _Expat Causing Apache Crash: http://www.dscpl.com.au/articles/modpython-006.html
  287. .. _mod_python FAQ entry: http://modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp
  288. .. _Getting mod_python Working: http://www.dscpl.com.au/articles/modpython-001.html