modpython.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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
  15. AJP <howto-deployment-fastcgi>`.
  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. (or in different ``VirtualHost`` blocks that share the same server name),
  127. you'll need to take a special precaution to ensure mod_python's cache doesn't
  128. mess things up. Use the ``PythonInterpreter`` directive to give different
  129. ``<Location>`` directives separate interpreters::
  130. <VirtualHost *>
  131. ServerName www.example.com
  132. # ...
  133. <Location "/something">
  134. SetEnv DJANGO_SETTINGS_MODULE mysite.settings
  135. PythonInterpreter mysite
  136. </Location>
  137. <Location "/otherthing">
  138. SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
  139. PythonInterpreter othersite
  140. </Location>
  141. </VirtualHost>
  142. The values of ``PythonInterpreter`` don't really matter, as long as they're
  143. different between the two ``Location`` blocks.
  144. Running a development server with mod_python
  145. ============================================
  146. If you use mod_python for your development server, you can avoid the hassle of
  147. having to restart the server each time you make code changes. Just set
  148. ``MaxRequestsPerChild 1`` in your ``httpd.conf`` file to force Apache to reload
  149. everything for each request. But don't do that on a production server, or we'll
  150. revoke your Django privileges.
  151. If you're the type of programmer who debugs using scattered ``print``
  152. statements, note that ``print`` statements have no effect in mod_python; they
  153. don't appear in the Apache log, as one might expect. If you have the need to
  154. print debugging information in a mod_python setup, either do this::
  155. assert False, the_value_i_want_to_see
  156. Or add the debugging information to the template of your page.
  157. .. _mod_python documentation: http://modpython.org/live/current/doc-html/directives.html
  158. .. _serving-media-files:
  159. Serving media files
  160. ===================
  161. Django doesn't serve media files itself; it leaves that job to whichever Web
  162. server you choose.
  163. We recommend using a separate Web server -- i.e., one that's not also running
  164. Django -- for serving media. Here are some good choices:
  165. * lighttpd_
  166. * TUX_
  167. * A stripped-down version of Apache_
  168. If, however, you have no option but to serve media files on the same Apache
  169. ``VirtualHost`` as Django, here's how you can turn off mod_python for a
  170. particular part of the site::
  171. <Location "/media">
  172. SetHandler None
  173. </Location>
  174. Just change ``Location`` to the root URL of your media files. You can also use
  175. ``<LocationMatch>`` to match a regular expression.
  176. This example sets up Django at the site root but explicitly disables Django for
  177. the ``media`` subdirectory and any URL that ends with ``.jpg``, ``.gif`` or
  178. ``.png``::
  179. <Location "/">
  180. SetHandler python-program
  181. PythonHandler django.core.handlers.modpython
  182. SetEnv DJANGO_SETTINGS_MODULE mysite.settings
  183. </Location>
  184. <Location "/media">
  185. SetHandler None
  186. </Location>
  187. <LocationMatch "\.(jpg|gif|png)$">
  188. SetHandler None
  189. </LocationMatch>
  190. .. _lighttpd: http://www.lighttpd.net/
  191. .. _TUX: http://en.wikipedia.org/wiki/TUX_web_server
  192. .. _Apache: http://httpd.apache.org/
  193. .. _howto-deployment-modpython-serving-the-admin-files:
  194. .. _serving-the-admin-files:
  195. Serving the admin files
  196. =======================
  197. Note that the Django development server automagically serves admin media files,
  198. but this is not the case when you use any other server arrangement. You're
  199. responsible for setting up Apache, or whichever media server you're using, to
  200. serve the admin files.
  201. The admin files live in (:file:`django/contrib/admin/media`) of the Django
  202. distribution.
  203. Here are two recommended approaches:
  204. 1. Create a symbolic link to the admin media files from within your
  205. document root. This way, all of your Django-related files -- code **and**
  206. templates -- stay in one place, and you'll still be able to ``svn
  207. update`` your code to get the latest admin templates, if they change.
  208. 2. Or, copy the admin media files so that they live within your Apache
  209. document root.
  210. Using "eggs" with mod_python
  211. ============================
  212. If you installed Django from a Python egg_ or are using eggs in your Django
  213. project, some extra configuration is required. Create an extra file in your
  214. project (or somewhere else) that contains something like the following:
  215. .. code-block:: python
  216. import os
  217. os.environ['PYTHON_EGG_CACHE'] = '/some/directory'
  218. Here, ``/some/directory`` is a directory that the Apache webserver process can
  219. write to. It will be used as the location for any unpacking of code the eggs
  220. need to do.
  221. Then you have to tell mod_python to import this file before doing anything
  222. else. This is done using the PythonImport_ directive to mod_python. You need
  223. to ensure that you have specified the ``PythonInterpreter`` directive to
  224. mod_python as described above__ (you need to do this even if you aren't
  225. serving multiple installations in this case). Then add the ``PythonImport``
  226. line in the main server configuration (i.e., outside the ``Location`` or
  227. ``VirtualHost`` sections). For example::
  228. PythonInterpreter my_django
  229. PythonImport /path/to/my/project/file.py my_django
  230. Note that you can use an absolute path here (or a normal dotted import path),
  231. as described in the `mod_python manual`_. We use an absolute path in the
  232. above example because if any Python path modifications are required to access
  233. your project, they will not have been done at the time the ``PythonImport``
  234. line is processed.
  235. .. _Egg: http://peak.telecommunity.com/DevCenter/PythonEggs
  236. .. _PythonImport: http://www.modpython.org/live/current/doc-html/dir-other-pimp.html
  237. .. _mod_python manual: PythonImport_
  238. __ `Multiple Django installations on the same Apache`_
  239. Error handling
  240. ==============
  241. When you use Apache/mod_python, errors will be caught by Django -- in other
  242. words, they won't propagate to the Apache level and won't appear in the Apache
  243. ``error_log``.
  244. The exception for this is if something is really wonky in your Django setup. In
  245. that case, you'll see an "Internal Server Error" page in your browser and the
  246. full Python traceback in your Apache ``error_log`` file. The ``error_log``
  247. traceback is spread over multiple lines. (Yes, this is ugly and rather hard to
  248. read, but it's how mod_python does things.)
  249. If you get a segmentation fault
  250. ===============================
  251. If Apache causes a segmentation fault, there are two probable causes, neither
  252. of which has to do with Django itself.
  253. 1. It may be because your Python code is importing the "pyexpat" module,
  254. which may conflict with the version embedded in Apache. For full
  255. information, see `Expat Causing Apache Crash`_.
  256. 2. It may be because you're running mod_python and mod_php in the same
  257. Apache instance, with MySQL as your database backend. In some cases,
  258. this causes a known mod_python issue due to version conflicts in PHP and
  259. the Python MySQL backend. There's full information in the
  260. `mod_python FAQ entry`_.
  261. If you continue to have problems setting up mod_python, a good thing to do is
  262. get a barebones mod_python site working, without the Django framework. This is
  263. an easy way to isolate mod_python-specific problems. `Getting mod_python Working`_
  264. details this procedure.
  265. The next step should be to edit your test code and add an import of any
  266. Django-specific code you're using -- your views, your models, your URLconf,
  267. your RSS configuration, etc. Put these imports in your test handler function
  268. and access your test URL in a browser. If this causes a crash, you've confirmed
  269. it's the importing of Django code that causes the problem. Gradually reduce the
  270. set of imports until it stops crashing, so as to find the specific module that
  271. causes the problem. Drop down further into modules and look into their imports,
  272. as necessary.
  273. .. _Expat Causing Apache Crash: http://www.dscpl.com.au/articles/modpython-006.html
  274. .. _mod_python FAQ entry: http://modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp
  275. .. _Getting mod_python Working: http://www.dscpl.com.au/articles/modpython-001.html