modpython.txt 17 KB

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