1.0 beta 1 release notes
[django.git] / docs / modpython.txt
blob44de0e1bd261f4c88ad4461c4aa4cc80ebbdc845
1 =================================
2 How to use Django with mod_python
3 =================================
5 Apache_ with `mod_python`_ currently is the preferred setup for using Django
6 on a production server.
8 mod_python is similar to `mod_perl`_ : It embeds Python within Apache and loads
9 Python code into memory when the server starts. Code stays in memory throughout
10 the life of an Apache process, which leads to significant performance gains over
11 other server arrangements.
13 Django requires Apache 2.x and mod_python 3.x, and you should use Apache's
14 `prefork MPM`_, as opposed to the `worker MPM`_.
16 You may also be interested in `How to use Django with FastCGI, SCGI or AJP`_
17 (which also covers SCGI and AJP).
19 .. _Apache: http://httpd.apache.org/
20 .. _mod_python: http://www.modpython.org/
21 .. _mod_perl: http://perl.apache.org/
22 .. _prefork MPM: http://httpd.apache.org/docs/2.2/mod/prefork.html
23 .. _worker MPM: http://httpd.apache.org/docs/2.2/mod/worker.html
24 .. _How to use Django with FastCGI, SCGI or AJP: ../fastcgi/
26 Basic configuration
27 ===================
29 To configure Django with mod_python, first make sure you have Apache installed,
30 with the mod_python module activated.
32 Then edit your ``httpd.conf`` file and add the following::
34     <Location "/mysite/">
35         SetHandler python-program
36         PythonHandler django.core.handlers.modpython
37         SetEnv DJANGO_SETTINGS_MODULE mysite.settings
38         PythonOption django.root /mysite
39         PythonDebug On
40     </Location>
42 ...and replace ``mysite.settings`` with the Python import path to your Django
43 project's settings file.
45 This tells Apache: "Use mod_python for any URL at or under '/mysite/', using the
46 Django mod_python handler." It passes the value of ``DJANGO_SETTINGS_MODULE``
47 so mod_python knows which settings to use.
49 **New in Django development version:** Because mod_python does not know we are
50 serving this site from underneath the ``/mysite/`` prefix, this value needs to
51 be passed through to the mod_python handler in Django, via the ``PythonOption
52 django.root ...`` line. The value set on that line (the last item) should
53 match the string given in the ``<Location ...>`` directive. The effect of this
54 is that Django will automatically strip the ``/mysite`` string from the front
55 of any URLs before matching them against your ``URLConf`` patterns. If you
56 later move your site to live under ``/mysite2``, you will not have to change
57 anything except the ``django.root`` option in the config 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.
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.
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:
75 .. parsed-literal::
77     <Location "/mysite/">
78         SetHandler python-program
79         PythonHandler django.core.handlers.modpython
80         SetEnv DJANGO_SETTINGS_MODULE mysite.settings
81         PythonOption django.root /mysite
82         PythonDebug On
83         **PythonPath "['/path/to/project'] + sys.path"**
84     </Location>
86 The value you use for ``PythonPath`` should include the parent directories of
87 all the modules you are going to import in your application. It should also
88 include the parent directory of the ``DJANGO_SETTINGS_MODULE`` location. This
89 is exactly the same situation as setting the Python path for interactive
90 usage. Whenever you try to import something, Python will run through all the
91 directories in ``sys.path`` in turn, from first to last, and try to import
92 from each directory until one succeeds.
94 An example might make this clearer. Suppose
95 you have some applications under ``/usr/local/django-apps/`` (for example,
96 ``/usr/local/django-apps/weblog/`` and so forth), your settings file is at
97 ``/var/www/mysite/settings.py`` and you have specified
98 ``DJANGO_SETTINGS_MODULE`` as in the above example. In this case, you would
99 need to write your ``PythonPath`` directive as::
101         PythonPath "['/usr/local/django-apps/', '/var/www'] + sys.path"
103 With this path, ``import weblog`` and ``import mysite.settings`` will both
104 work. If you had ``import blogroll`` in your code somewhere and ``blogroll``
105 lived under the ``weblog/`` directory, you would *also* need to add
106 ``/usr/local/django-apps/weblog/`` to your ``PythonPath``. Remember: the
107 **parent directories** of anything you import directly must be on the Python
108 path.
110 .. note::
112     If you're using Windows, we still recommended that you use forward
113     slashes in the pathnames, even though Windows normally uses the backslash
114     character as its native separator. Apache knows how to convert from the
115     forward slash format to the native format, so this approach is portable and
116     easier to read. (It avoids tricky problems with having to double-escape
117     backslashes.)
119     This is valid even on a Windows system::
121         PythonPath "['c:/path/to/project'] + sys.path"
123 You can also add directives such as ``PythonAutoReload Off`` for performance.
124 See the `mod_python documentation`_ for a full list of options.
126 Note that you should set ``PythonDebug Off`` on a production server. If you
127 leave ``PythonDebug On``, your users would see ugly (and revealing) Python
128 tracebacks if something goes wrong within mod_python.
130 Restart Apache, and any request to /mysite/ or below will be served by Django.
131 Note that Django's URLconfs won't trim the "/mysite/" -- they get passed the
132 full URL.
134 When deploying Django sites on mod_python, you'll need to restart Apache each
135 time you make changes to your Python code.
137 Multiple Django installations on the same Apache
138 ================================================
140 It's entirely possible to run multiple Django installations on the same Apache
141 instance. Just use ``VirtualHost`` for that, like so::
143     NameVirtualHost *
145     <VirtualHost *>
146         ServerName www.example.com
147         # ...
148         SetEnv DJANGO_SETTINGS_MODULE mysite.settings
149     </VirtualHost>
151     <VirtualHost *>
152         ServerName www2.example.com
153         # ...
154         SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
155     </VirtualHost>
157 If you need to put two Django installations within the same ``VirtualHost``,
158 you'll need to take a special precaution to ensure mod_python's cache doesn't
159 mess things up. Use the ``PythonInterpreter`` directive to give different
160 ``<Location>`` directives separate interpreters::
162     <VirtualHost *>
163         ServerName www.example.com
164         # ...
165         <Location "/something">
166             SetEnv DJANGO_SETTINGS_MODULE mysite.settings
167             PythonInterpreter mysite
168         </Location>
170         <Location "/otherthing">
171             SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
172             PythonInterpreter othersite
173         </Location>
174     </VirtualHost>
176 The values of ``PythonInterpreter`` don't really matter, as long as they're
177 different between the two ``Location`` blocks.
179 Running a development server with mod_python
180 ============================================
182 If you use mod_python for your development server, you can avoid the hassle of
183 having to restart the server each time you make code changes. Just set
184 ``MaxRequestsPerChild 1`` in your ``httpd.conf`` file to force Apache to reload
185 everything for each request. But don't do that on a production server, or we'll
186 revoke your Django privileges.
188 If you're the type of programmer who debugs using scattered ``print``
189 statements, note that ``print`` statements have no effect in mod_python; they
190 don't appear in the Apache log, as one might expect. If you have the need to
191 print debugging information in a mod_python setup, either do this::
193     assert False, the_value_i_want_to_see
195 Or add the debugging information to the template of your page.
197 .. _mod_python documentation: http://modpython.org/live/current/doc-html/directives.html
199 Serving media files
200 ===================
202 Django doesn't serve media files itself; it leaves that job to whichever Web
203 server you choose.
205 We recommend using a separate Web server -- i.e., one that's not also running
206 Django -- for serving media. Here are some good choices:
208 * lighttpd_
209 * TUX_
210 * A stripped-down version of Apache_
212 If, however, you have no option but to serve media files on the same Apache
213 ``VirtualHost`` as Django, here's how you can turn off mod_python for a
214 particular part of the site::
216     <Location "/media">
217         SetHandler None
218     </Location>
220 Just change ``Location`` to the root URL of your media files. You can also use
221 ``<LocationMatch>`` to match a regular expression.
223 This example sets up Django at the site root but explicitly disables Django for
224 the ``media`` subdirectory and any URL that ends with ``.jpg``, ``.gif`` or
225 ``.png``::
227     <Location "/">
228         SetHandler python-program
229         PythonHandler django.core.handlers.modpython
230         SetEnv DJANGO_SETTINGS_MODULE mysite.settings
231     </Location>
233     <Location "/media">
234         SetHandler None
235     </Location>
237     <LocationMatch "\.(jpg|gif|png)$">
238         SetHandler None
239     </LocationMatch>
242 .. _lighttpd: http://www.lighttpd.net/
243 .. _TUX: http://en.wikipedia.org/wiki/TUX_web_server
244 .. _Apache: http://httpd.apache.org/
246 Serving the admin files
247 =======================
249 Note that the Django development server automagically serves admin media files,
250 but this is not the case when you use any other server arrangement. You're
251 responsible for setting up Apache, or whichever media server you're using, to
252 serve the admin files.
254 The admin files live in (``django/contrib/admin/media``) of the Django
255 distribution.
257 Here are two recommended approaches:
259     1. Create a symbolic link to the admin media files from within your
260        document root. This way, all of your Django-related files -- code
261        **and** templates -- stay in one place, and you'll still be able to
262        ``svn update`` your code to get the latest admin templates, if they
263        change.
264     2. Or, copy the admin media files so that they live within your Apache
265        document root.
267 Using eggs with mod_python
268 ==========================
270 If you installed Django from a Python egg_ or are using eggs in your Django
271 project, some extra configuration is required. Create an extra file in your
272 project (or somewhere else) that contains something like the following::
274     import os
275     os.environ['PYTHON_EGG_CACHE'] = '/some/directory'
277 Here, ``/some/directory`` is a directory that the Apache webserver process can
278 write to. It will be used as the location for any unpacking of code the eggs
279 need to do.
281 Then you have to tell mod_python to import this file before doing anything
282 else. This is done using the PythonImport_ directive to mod_python. You need
283 to ensure that you have specified the ``PythonInterpreter`` directive to
284 mod_python as described above__ (you need to do this even if you aren't
285 serving multiple installations in this case). Then add the ``PythonImport``
286 line in the main server configuration (i.e., outside the ``Location`` or
287 ``VirtualHost`` sections). For example::
289     PythonInterpreter my_django
290     PythonImport /path/to/my/project/file.py my_django
292 Note that you can use an absolute path here (or a normal dotted import path),
293 as described in the `mod_python manual`_. We use an absolute path in the
294 above example because if any Python path modifications are required to access
295 your project, they will not have been done at the time the ``PythonImport``
296 line is processed.
298 .. _Egg: http://peak.telecommunity.com/DevCenter/PythonEggs
299 .. _PythonImport: http://www.modpython.org/live/current/doc-html/dir-other-pimp.html
300 .. _mod_python manual: PythonImport_
301 __ `Multiple Django installations on the same Apache`_
303 Error handling
304 ==============
306 When you use Apache/mod_python, errors will be caught by Django -- in other
307 words, they won't propagate to the Apache level and won't appear in the Apache
308 ``error_log``.
310 The exception for this is if something is really wonky in your Django setup. In
311 that case, you'll see an "Internal Server Error" page in your browser and the
312 full Python traceback in your Apache ``error_log`` file. The ``error_log``
313 traceback is spread over multiple lines. (Yes, this is ugly and rather hard to
314 read, but it's how mod_python does things.)
316 If you get a segmentation fault
317 ===============================
319 If Apache causes a segmentation fault, there are two probable causes, neither
320 of which has to do with Django itself.
322     1. It may be because your Python code is importing the "pyexpat" module,
323        which may conflict with the version embedded in Apache. For full
324        information, see `Expat Causing Apache Crash`_.
325     2. It may be because you're running mod_python and mod_php in the same
326        Apache instance, with MySQL as your database backend. In some cases,
327        this causes a known mod_python issue due to version conflicts in PHP and
328        the Python MySQL backend. There's full information in the
329        `mod_python FAQ entry`_.
331 If you continue to have problems setting up mod_python, a good thing to do is
332 get a barebones mod_python site working, without the Django framework. This is
333 an easy way to isolate mod_python-specific problems. `Getting mod_python Working`_
334 details this procedure.
336 The next step should be to edit your test code and add an import of any
337 Django-specific code you're using -- your views, your models, your URLconf,
338 your RSS configuration, etc. Put these imports in your test handler function
339 and access your test URL in a browser. If this causes a crash, you've confirmed
340 it's the importing of Django code that causes the problem. Gradually reduce the
341 set of imports until it stops crashing, so as to find the specific module that
342 causes the problem. Drop down further into modules and look into their imports,
343 as necessary.
345 .. _Expat Causing Apache Crash: http://www.dscpl.com.au/articles/modpython-006.html
346 .. _mod_python FAQ entry: http://modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp
347 .. _Getting mod_python Working: http://www.dscpl.com.au/articles/modpython-001.html