modpython.txt 17 KB

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