modpython.txt 17 KB

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