modpython.txt 15 KB

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