diff options
author | Nishanth Amuluru | 2011-01-08 11:20:57 +0530 |
---|---|---|
committer | Nishanth Amuluru | 2011-01-08 11:20:57 +0530 |
commit | 65411d01d448ff0cd4abd14eee14cf60b5f8fc20 (patch) | |
tree | b4c404363c4c63a61d6e2f8bd26c5b057c1fb09d /parts/django/docs/howto/deployment | |
parent | 2e35094d43b4cc6974172e1febf76abb50f086ec (diff) | |
download | pytask-65411d01d448ff0cd4abd14eee14cf60b5f8fc20.tar.gz pytask-65411d01d448ff0cd4abd14eee14cf60b5f8fc20.tar.bz2 pytask-65411d01d448ff0cd4abd14eee14cf60b5f8fc20.zip |
Added buildout stuff and made changes accordingly
--HG--
rename : profile/management/__init__.py => eggs/djangorecipe-0.20-py2.6.egg/EGG-INFO/dependency_links.txt
rename : profile/management/__init__.py => eggs/djangorecipe-0.20-py2.6.egg/EGG-INFO/not-zip-safe
rename : profile/management/__init__.py => eggs/infrae.subversion-1.4.5-py2.6.egg/EGG-INFO/dependency_links.txt
rename : profile/management/__init__.py => eggs/infrae.subversion-1.4.5-py2.6.egg/EGG-INFO/not-zip-safe
rename : profile/management/__init__.py => eggs/mercurial-1.7.3-py2.6-linux-x86_64.egg/EGG-INFO/dependency_links.txt
rename : profile/management/__init__.py => eggs/mercurial-1.7.3-py2.6-linux-x86_64.egg/EGG-INFO/not-zip-safe
rename : profile/management/__init__.py => eggs/py-1.4.0-py2.6.egg/EGG-INFO/dependency_links.txt
rename : profile/management/__init__.py => eggs/py-1.4.0-py2.6.egg/EGG-INFO/not-zip-safe
rename : profile/management/__init__.py => eggs/zc.buildout-1.5.2-py2.6.egg/EGG-INFO/dependency_links.txt
rename : profile/management/__init__.py => eggs/zc.buildout-1.5.2-py2.6.egg/EGG-INFO/not-zip-safe
rename : profile/management/__init__.py => eggs/zc.recipe.egg-1.3.2-py2.6.egg/EGG-INFO/dependency_links.txt
rename : profile/management/__init__.py => eggs/zc.recipe.egg-1.3.2-py2.6.egg/EGG-INFO/not-zip-safe
rename : profile/management/__init__.py => parts/django/Django.egg-info/dependency_links.txt
rename : taskapp/models.py => parts/django/django/conf/app_template/models.py
rename : taskapp/tests.py => parts/django/django/conf/app_template/tests.py
rename : taskapp/views.py => parts/django/django/conf/app_template/views.py
rename : taskapp/views.py => parts/django/django/contrib/gis/tests/geo3d/views.py
rename : profile/management/__init__.py => parts/django/tests/modeltests/delete/__init__.py
rename : profile/management/__init__.py => parts/django/tests/modeltests/files/__init__.py
rename : profile/management/__init__.py => parts/django/tests/modeltests/invalid_models/__init__.py
rename : profile/management/__init__.py => parts/django/tests/modeltests/m2m_signals/__init__.py
rename : profile/management/__init__.py => parts/django/tests/modeltests/model_package/__init__.py
rename : profile/management/__init__.py => parts/django/tests/regressiontests/bash_completion/__init__.py
rename : profile/management/__init__.py => parts/django/tests/regressiontests/bash_completion/management/__init__.py
rename : profile/management/__init__.py => parts/django/tests/regressiontests/bash_completion/management/commands/__init__.py
rename : profile/management/__init__.py => parts/django/tests/regressiontests/bash_completion/models.py
rename : profile/management/__init__.py => parts/django/tests/regressiontests/delete_regress/__init__.py
rename : profile/management/__init__.py => parts/django/tests/regressiontests/file_storage/__init__.py
rename : profile/management/__init__.py => parts/django/tests/regressiontests/max_lengths/__init__.py
rename : profile/forms.py => pytask/profile/forms.py
rename : profile/management/__init__.py => pytask/profile/management/__init__.py
rename : profile/management/commands/seed_db.py => pytask/profile/management/commands/seed_db.py
rename : profile/models.py => pytask/profile/models.py
rename : profile/templatetags/user_tags.py => pytask/profile/templatetags/user_tags.py
rename : taskapp/tests.py => pytask/profile/tests.py
rename : profile/urls.py => pytask/profile/urls.py
rename : profile/utils.py => pytask/profile/utils.py
rename : profile/views.py => pytask/profile/views.py
rename : static/css/base.css => pytask/static/css/base.css
rename : taskapp/tests.py => pytask/taskapp/tests.py
rename : taskapp/views.py => pytask/taskapp/views.py
rename : templates/base.html => pytask/templates/base.html
rename : templates/profile/browse_notifications.html => pytask/templates/profile/browse_notifications.html
rename : templates/profile/edit.html => pytask/templates/profile/edit.html
rename : templates/profile/view.html => pytask/templates/profile/view.html
rename : templates/profile/view_notification.html => pytask/templates/profile/view_notification.html
rename : templates/registration/activate.html => pytask/templates/registration/activate.html
rename : templates/registration/activation_email.txt => pytask/templates/registration/activation_email.txt
rename : templates/registration/activation_email_subject.txt => pytask/templates/registration/activation_email_subject.txt
rename : templates/registration/logged_out.html => pytask/templates/registration/logged_out.html
rename : templates/registration/login.html => pytask/templates/registration/login.html
rename : templates/registration/logout.html => pytask/templates/registration/logout.html
rename : templates/registration/password_change_done.html => pytask/templates/registration/password_change_done.html
rename : templates/registration/password_change_form.html => pytask/templates/registration/password_change_form.html
rename : templates/registration/password_reset_complete.html => pytask/templates/registration/password_reset_complete.html
rename : templates/registration/password_reset_confirm.html => pytask/templates/registration/password_reset_confirm.html
rename : templates/registration/password_reset_done.html => pytask/templates/registration/password_reset_done.html
rename : templates/registration/password_reset_email.html => pytask/templates/registration/password_reset_email.html
rename : templates/registration/password_reset_form.html => pytask/templates/registration/password_reset_form.html
rename : templates/registration/registration_complete.html => pytask/templates/registration/registration_complete.html
rename : templates/registration/registration_form.html => pytask/templates/registration/registration_form.html
rename : utils.py => pytask/utils.py
Diffstat (limited to 'parts/django/docs/howto/deployment')
-rw-r--r-- | parts/django/docs/howto/deployment/fastcgi.txt | 400 | ||||
-rw-r--r-- | parts/django/docs/howto/deployment/index.txt | 25 | ||||
-rw-r--r-- | parts/django/docs/howto/deployment/modpython.txt | 418 | ||||
-rw-r--r-- | parts/django/docs/howto/deployment/modwsgi.txt | 118 |
4 files changed, 961 insertions, 0 deletions
diff --git a/parts/django/docs/howto/deployment/fastcgi.txt b/parts/django/docs/howto/deployment/fastcgi.txt new file mode 100644 index 0000000..ea14b97 --- /dev/null +++ b/parts/django/docs/howto/deployment/fastcgi.txt @@ -0,0 +1,400 @@ +============================================ +How to use Django with FastCGI, SCGI, or AJP +============================================ + +.. highlight:: bash + +Although the current preferred setup for running Django is :doc:`Apache with +mod_wsgi </howto/deployment/modwsgi>`, many people use shared hosting, on +which protocols such as FastCGI, SCGI or AJP are the only viable options. In +some setups, these protocols may provide better performance than mod_wsgi_. + +.. admonition:: Note + + This document primarily focuses on FastCGI. Other protocols, such as SCGI + and AJP, are also supported, through the ``flup`` Python package. See the + Protocols_ section below for specifics about SCGI and AJP. + +Essentially, FastCGI is an efficient way of letting an external application +serve pages to a Web server. The Web server delegates the incoming Web requests +(via a socket) to FastCGI, which executes the code and passes the response back +to the Web server, which, in turn, passes it back to the client's Web browser. + +Like mod_python, FastCGI allows code to stay in memory, allowing requests to be +served with no startup time. Unlike mod_python_ (or `mod_perl`_), a FastCGI +process doesn't run inside the Web server process, but in a separate, +persistent process. + +.. _mod_wsgi: http://code.google.com/p/modwsgi/ +.. _mod_perl: http://perl.apache.org/ +.. _mod_python: http://www.modpython.org/ + +.. admonition:: Why run code in a separate process? + + The traditional ``mod_*`` arrangements in Apache embed various scripting + languages (most notably PHP, Python and Perl) inside the process space of + your Web server. Although this lowers startup time -- because code doesn't + have to be read off disk for every request -- it comes at the cost of + memory use. For mod_python, for example, every Apache process gets its own + Python interpreter, which uses up a considerable amount of RAM. + + Due to the nature of FastCGI, it's even possible to have processes that run + under a different user account than the Web server process. That's a nice + security benefit on shared systems, because it means you can secure your + code from other users. + +Prerequisite: flup +================== + +Before you can start using FastCGI with Django, you'll need to install flup_, a +Python library for dealing with FastCGI. Version 0.5 or newer should work fine. + +.. _flup: http://www.saddi.com/software/flup/ + +Starting your FastCGI server +============================ + +FastCGI operates on a client-server model, and in most cases you'll be starting +the FastCGI process on your own. Your Web server (be it Apache, lighttpd, or +otherwise) only contacts your Django-FastCGI process when the server needs a +dynamic page to be loaded. Because the daemon is already running with the code +in memory, it's able to serve the response very quickly. + +.. admonition:: Note + + If you're on a shared hosting system, you'll probably be forced to use + Web server-managed FastCGI processes. See the section below on running + Django with Web server-managed processes for more information. + +A Web server can connect to a FastCGI server in one of two ways: It can use +either a Unix domain socket (a "named pipe" on Win32 systems), or it can use a +TCP socket. What you choose is a manner of preference; a TCP socket is usually +easier due to permissions issues. + +To start your server, first change into the directory of your project (wherever +your :doc:`manage.py </ref/django-admin>` is), and then run the +:djadmin:`runfcgi` command:: + + ./manage.py runfcgi [options] + +If you specify ``help`` as the only option after :djadmin:`runfcgi`, it'll +display a list of all the available options. + +You'll need to specify either a :djadminopt:`socket`, a :djadminopt:`protocol` +or both :djadminopt:`host` and :djadminopt:`port`. Then, when you set up your +Web server, you'll just need to point it at the host/port or socket you +specified when starting the FastCGI server. See the examples_, below. + +Protocols +--------- + +Django supports all the protocols that flup_ does, namely fastcgi_, `SCGI`_ and +`AJP1.3`_ (the Apache JServ Protocol, version 1.3). Select your preferred +protocol by using the :djadminopt:`protocol=\<protocol_name\> <protocol>` option +with ``./manage.py runfcgi`` -- where ``<protocol_name>`` may be one of: +``fcgi`` (the default), ``scgi`` or ``ajp``. For example:: + + ./manage.py runfcgi protocol=scgi + +.. _flup: http://www.saddi.com/software/flup/ +.. _fastcgi: http://www.fastcgi.com/ +.. _SCGI: http://python.ca/scgi/protocol.txt +.. _AJP1.3: http://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html + +Examples +-------- + +Running a threaded server on a TCP port:: + + ./manage.py runfcgi method=threaded host=127.0.0.1 port=3033 + +Running a preforked server on a Unix domain socket:: + + ./manage.py runfcgi method=prefork socket=/home/user/mysite.sock pidfile=django.pid + +.. admonition:: Socket security + + Django's default umask requires that the webserver and the Django fastcgi + process be run with the same group **and** user. For increased security, + you can run them under the same group but as different users. If you do + this, you will need to set the umask to 0002 using the ``umask`` argument + to ``runfcgi``. + +Run without daemonizing (backgrounding) the process (good for debugging):: + + ./manage.py runfcgi daemonize=false socket=/tmp/mysite.sock maxrequests=1 + +Stopping the FastCGI daemon +--------------------------- + +If you have the process running in the foreground, it's easy enough to stop it: +Simply hitting ``Ctrl-C`` will stop and quit the FastCGI server. However, when +you're dealing with background processes, you'll need to resort to the Unix +``kill`` command. + +If you specify the :djadminopt:`pidfile` option to :djadmin:`runfcgi`, you can +kill the running FastCGI daemon like this:: + + kill `cat $PIDFILE` + +...where ``$PIDFILE`` is the ``pidfile`` you specified. + +To easily restart your FastCGI daemon on Unix, try this small shell script:: + + #!/bin/bash + + # Replace these three settings. + PROJDIR="/home/user/myproject" + PIDFILE="$PROJDIR/mysite.pid" + SOCKET="$PROJDIR/mysite.sock" + + cd $PROJDIR + if [ -f $PIDFILE ]; then + kill `cat -- $PIDFILE` + rm -f -- $PIDFILE + fi + + exec /usr/bin/env - \ + PYTHONPATH="../python:.." \ + ./manage.py runfcgi socket=$SOCKET pidfile=$PIDFILE + +Apache setup +============ + +To use Django with Apache and FastCGI, you'll need Apache installed and +configured, with `mod_fastcgi`_ installed and enabled. Consult the Apache +documentation for instructions. + +Once you've got that set up, point Apache at your Django FastCGI instance by +editing the ``httpd.conf`` (Apache configuration) file. You'll need to do two +things: + + * Use the ``FastCGIExternalServer`` directive to specify the location of + your FastCGI server. + * Use ``mod_rewrite`` to point URLs at FastCGI as appropriate. + +.. _mod_fastcgi: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html + +Specifying the location of the FastCGI server +--------------------------------------------- + +The ``FastCGIExternalServer`` directive tells Apache how to find your FastCGI +server. As the `FastCGIExternalServer docs`_ explain, you can specify either a +``socket`` or a ``host``. Here are examples of both: + +.. code-block:: apache + + # Connect to FastCGI via a socket / named pipe. + FastCGIExternalServer /home/user/public_html/mysite.fcgi -socket /home/user/mysite.sock + + # Connect to FastCGI via a TCP host/port. + FastCGIExternalServer /home/user/public_html/mysite.fcgi -host 127.0.0.1:3033 + +In either case, the file ``/home/user/public_html/mysite.fcgi`` doesn't +actually have to exist. It's just a URL used by the Web server internally -- a +hook for signifying which requests at a URL should be handled by FastCGI. (More +on this in the next section.) + +.. _FastCGIExternalServer docs: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html#FastCgiExternalServer + +Using mod_rewrite to point URLs at FastCGI +------------------------------------------ + +The second step is telling Apache to use FastCGI for URLs that match a certain +pattern. To do this, use the `mod_rewrite`_ module and rewrite URLs to +``mysite.fcgi`` (or whatever you specified in the ``FastCGIExternalServer`` +directive, as explained in the previous section). + +In this example, we tell Apache to use FastCGI to handle any request that +doesn't represent a file on the filesystem and doesn't start with ``/media/``. +This is probably the most common case, if you're using Django's admin site: + +.. code-block:: apache + + <VirtualHost 12.34.56.78> + ServerName example.com + DocumentRoot /home/user/public_html + Alias /media /home/user/python/django/contrib/admin/media + RewriteEngine On + RewriteRule ^/(media.*)$ /$1 [QSA,L,PT] + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^/(.*)$ /mysite.fcgi/$1 [QSA,L] + </VirtualHost> + +.. _mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html + +Django will automatically use the pre-rewrite version of the URL when +constructing URLs with the ``{% url %}`` template tag (and similar methods). + +lighttpd setup +============== + +lighttpd_ is a lightweight Web server commonly used for serving static files. It +supports FastCGI natively and, thus, is a good choice for serving both static +and dynamic pages, if your site doesn't have any Apache-specific needs. + +.. _lighttpd: http://www.lighttpd.net/ + +Make sure ``mod_fastcgi`` is in your modules list, somewhere after +``mod_rewrite`` and ``mod_access``, but not after ``mod_accesslog``. You'll +probably want ``mod_alias`` as well, for serving admin media. + +Add the following to your lighttpd config file: + +.. code-block:: lua + + server.document-root = "/home/user/public_html" + fastcgi.server = ( + "/mysite.fcgi" => ( + "main" => ( + # Use host / port instead of socket for TCP fastcgi + # "host" => "127.0.0.1", + # "port" => 3033, + "socket" => "/home/user/mysite.sock", + "check-local" => "disable", + ) + ), + ) + alias.url = ( + "/media" => "/home/user/django/contrib/admin/media/", + ) + + url.rewrite-once = ( + "^(/media.*)$" => "$1", + "^/favicon\.ico$" => "/media/favicon.ico", + "^(/.*)$" => "/mysite.fcgi$1", + ) + +Running multiple Django sites on one lighttpd +--------------------------------------------- + +lighttpd lets you use "conditional configuration" to allow configuration to be +customized per host. To specify multiple FastCGI sites, just add a conditional +block around your FastCGI config for each site:: + + # If the hostname is 'www.example1.com'... + $HTTP["host"] == "www.example1.com" { + server.document-root = "/foo/site1" + fastcgi.server = ( + ... + ) + ... + } + + # If the hostname is 'www.example2.com'... + $HTTP["host"] == "www.example2.com" { + server.document-root = "/foo/site2" + fastcgi.server = ( + ... + ) + ... + } + +You can also run multiple Django installations on the same site simply by +specifying multiple entries in the ``fastcgi.server`` directive. Add one +FastCGI host for each. + +Cherokee setup +============== + +Cherokee is a very fast, flexible and easy to configure Web Server. It +supports the widespread technologies nowadays: FastCGI, SCGI, PHP, CGI, SSI, +TLS and SSL encrypted connections, Virtual hosts, Authentication, on the fly +encoding, Load Balancing, Apache compatible log files, Data Base Balancer, +Reverse HTTP Proxy and much more. + +The Cherokee project provides a documentation to `setting up Django`_ with Cherokee. + +.. _setting up Django: http://www.cherokee-project.com/doc/cookbook_django.html + +Running Django on a shared-hosting provider with Apache +======================================================= + +Many shared-hosting providers don't allow you to run your own server daemons or +edit the ``httpd.conf`` file. In these cases, it's still possible to run Django +using Web server-spawned processes. + +.. admonition:: Note + + If you're using Web server-spawned processes, as explained in this section, + there's no need for you to start the FastCGI server on your own. Apache + will spawn a number of processes, scaling as it needs to. + +In your Web root directory, add this to a file named ``.htaccess``: + +.. code-block:: apache + + AddHandler fastcgi-script .fcgi + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L] + +Then, create a small script that tells Apache how to spawn your FastCGI +program. Create a file ``mysite.fcgi`` and place it in your Web directory, and +be sure to make it executable: + +.. code-block:: python + + #!/usr/bin/python + import sys, os + + # Add a custom Python path. + sys.path.insert(0, "/home/user/python") + + # Switch to the directory of your project. (Optional.) + # os.chdir("/home/user/myproject") + + # Set the DJANGO_SETTINGS_MODULE environment variable. + os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings" + + from django.core.servers.fastcgi import runfastcgi + runfastcgi(method="threaded", daemonize="false") + +Restarting the spawned server +----------------------------- + +If you change any Python code on your site, you'll need to tell FastCGI the +code has changed. But there's no need to restart Apache in this case. Rather, +just reupload ``mysite.fcgi``, or edit the file, so that the timestamp on the +file will change. When Apache sees the file has been updated, it will restart +your Django application for you. + +If you have access to a command shell on a Unix system, you can accomplish this +easily by using the ``touch`` command:: + + touch mysite.fcgi + +Serving admin media files +========================= + +Regardless of the server and configuration you eventually decide to use, you +will also need to give some thought to how to serve the admin media files. The +advice given in the :ref:`modpython <serving-the-admin-files>` documentation +is also applicable in the setups detailed above. + +Forcing the URL prefix to a particular value +============================================ + +Because many of these fastcgi-based solutions require rewriting the URL at +some point inside the Web server, the path information that Django sees may not +resemble the original URL that was passed in. This is a problem if the Django +application is being served from under a particular prefix and you want your +URLs from the ``{% url %}`` tag to look like the prefix, rather than the +rewritten version, which might contain, for example, ``mysite.fcgi``. + +Django makes a good attempt to work out what the real script name prefix +should be. In particular, if the Web server sets the ``SCRIPT_URL`` (specific +to Apache's mod_rewrite), or ``REDIRECT_URL`` (set by a few servers, including +Apache + mod_rewrite in some situations), Django will work out the original +prefix automatically. + +In the cases where Django cannot work out the prefix correctly and where you +want the original value to be used in URLs, you can set the +:setting:`FORCE_SCRIPT_NAME` setting in your main ``settings`` file. This sets the +script name uniformly for every URL served via that settings file. Thus you'll +need to use different settings files if you want different sets of URLs to +have different script names in this case, but that is a rare situation. + +As an example of how to use it, if your Django configuration is serving all of +the URLs under ``'/'`` and you wanted to use this setting, you would set +``FORCE_SCRIPT_NAME = ''`` in your settings file. diff --git a/parts/django/docs/howto/deployment/index.txt b/parts/django/docs/howto/deployment/index.txt new file mode 100644 index 0000000..740f9bc --- /dev/null +++ b/parts/django/docs/howto/deployment/index.txt @@ -0,0 +1,25 @@ +Deploying Django +================ + +Django's chock-full of shortcuts to make Web developer's lives easier, but all +those tools are of no use if you can't easily deploy your sites. Since Django's +inception, ease of deployment has been a major goal. There's a number of good +ways to easily deploy Django: + +.. toctree:: + :maxdepth: 1 + + modwsgi + modpython + fastcgi + +If you're new to deploying Django and/or Python, we'd recommend you try +:doc:`mod_wsgi </howto/deployment/modwsgi>` first. In most cases it'll be the easiest, +fastest, and most stable deployment choice. + +.. seealso:: + + * `Chapter 12 of The Django Book`_ discusses deployment and especially + scaling in more detail. + +.. _chapter 12 of the django book: http://djangobook.com/en/2.0/chapter12/ diff --git a/parts/django/docs/howto/deployment/modpython.txt b/parts/django/docs/howto/deployment/modpython.txt new file mode 100644 index 0000000..ba55335 --- /dev/null +++ b/parts/django/docs/howto/deployment/modpython.txt @@ -0,0 +1,418 @@ +.. _howto-deployment-modpython: + +============================================ +How to use Django with Apache and mod_python +============================================ + +.. warning:: + + Support for mod_python will be deprecated in a future release of Django. If + you are configuring a new deployment, you are strongly encouraged to + consider using :doc:`mod_wsgi </howto/deployment/modwsgi>` or any of the + other :doc:`supported backends </howto/deployment/index>`. + +.. highlight:: apache + +The `mod_python`_ module for Apache_ can be used to deploy Django to a +production server, although it has been mostly superseded by the simpler +:doc:`mod_wsgi deployment option </howto/deployment/modwsgi>`. + +mod_python is similar to (and inspired by) `mod_perl`_ : It embeds Python within +Apache and loads Python code into memory when the server starts. Code stays in +memory throughout the life of an Apache process, which leads to significant +performance gains over other server arrangements. + +Django requires Apache 2.x and mod_python 3.x, and you should use Apache's +`prefork MPM`_, as opposed to the `worker MPM`_. + +.. seealso:: + + * Apache is a big, complex animal, and this document only scratches the + surface of what Apache can do. If you need more advanced information about + Apache, there's no better source than `Apache's own official + documentation`_ + + * You may also be interested in :doc:`How to use Django with FastCGI, SCGI, + or AJP </howto/deployment/fastcgi>`. + +.. _Apache: http://httpd.apache.org/ +.. _mod_python: http://www.modpython.org/ +.. _mod_perl: http://perl.apache.org/ +.. _prefork MPM: http://httpd.apache.org/docs/2.2/mod/prefork.html +.. _worker MPM: http://httpd.apache.org/docs/2.2/mod/worker.html +.. _apache's own official documentation: http://httpd.apache.org/docs/ + +Basic configuration +=================== + +To configure Django with mod_python, first make sure you have Apache installed, +with the mod_python module activated. + +Then edit your ``httpd.conf`` file and add the following:: + + <Location "/mysite/"> + SetHandler python-program + PythonHandler django.core.handlers.modpython + SetEnv DJANGO_SETTINGS_MODULE mysite.settings + PythonOption django.root /mysite + PythonDebug On + </Location> + +...and replace ``mysite.settings`` with the Python import path to your Django +project's settings file. + +This tells Apache: "Use mod_python for any URL at or under '/mysite/', using the +Django mod_python handler." It passes the value of :ref:`DJANGO_SETTINGS_MODULE +<django-settings-module>` so mod_python knows which settings to use. + +.. versionadded:: 1.0 + The ``PythonOption django.root ...`` is new in this version. + +Because mod_python does not know we are serving this site from underneath the +``/mysite/`` prefix, this value needs to be passed through to the mod_python +handler in Django, via the ``PythonOption django.root ...`` line. The value set +on that line (the last item) should match the string given in the ``<Location +...>`` directive. The effect of this is that Django will automatically strip the +``/mysite`` string from the front of any URLs before matching them against your +URLconf patterns. If you later move your site to live under ``/mysite2``, you +will not have to change anything except the ``django.root`` option in the config +file. + +When using ``django.root`` you should make sure that what's left, after the +prefix has been removed, begins with a slash. Your URLconf patterns that are +expecting an initial slash will then work correctly. In the above example, +since we want to send things like ``/mysite/admin/`` to ``/admin/``, we need +to remove the string ``/mysite`` from the beginning, so that is the +``django.root`` value. It would be an error to use ``/mysite/`` (with a +trailing slash) in this case. + +Note that we're using the ``<Location>`` directive, not the ``<Directory>`` +directive. The latter is used for pointing at places on your filesystem, +whereas ``<Location>`` points at places in the URL structure of a Web site. +``<Directory>`` would be meaningless here. + +Also, if your Django project is not on the default ``PYTHONPATH`` for your +computer, you'll have to tell mod_python where your project can be found: + +.. parsed-literal:: + + <Location "/mysite/"> + SetHandler python-program + PythonHandler django.core.handlers.modpython + SetEnv DJANGO_SETTINGS_MODULE mysite.settings + PythonOption django.root /mysite + PythonDebug On + **PythonPath "['/path/to/project'] + sys.path"** + </Location> + +The value you use for ``PythonPath`` should include the parent directories of +all the modules you are going to import in your application. It should also +include the parent directory of the :ref:`DJANGO_SETTINGS_MODULE +<django-settings-module>` location. This is exactly the same situation as +setting the Python path for interactive usage. Whenever you try to import +something, Python will run through all the directories in ``sys.path`` in turn, +from first to last, and try to import from each directory until one succeeds. + +Make sure that your Python source files' permissions are set such that the +Apache user (usually named ``apache`` or ``httpd`` on most systems) will have +read access to the files. + +An example might make this clearer. Suppose you have some applications under +``/usr/local/django-apps/`` (for example, ``/usr/local/django-apps/weblog/`` and +so forth), your settings file is at ``/var/www/mysite/settings.py`` and you have +specified :ref:`DJANGO_SETTINGS_MODULE <django-settings-module>` as in the above +example. In this case, you would need to write your ``PythonPath`` directive +as:: + + PythonPath "['/usr/local/django-apps/', '/var/www'] + sys.path" + +With this path, ``import weblog`` and ``import mysite.settings`` will both +work. If you had ``import blogroll`` in your code somewhere and ``blogroll`` +lived under the ``weblog/`` directory, you would *also* need to add +``/usr/local/django-apps/weblog/`` to your ``PythonPath``. Remember: the +**parent directories** of anything you import directly must be on the Python +path. + +.. note:: + + If you're using Windows, we still recommended that you use forward + slashes in the pathnames, even though Windows normally uses the backslash + character as its native separator. Apache knows how to convert from the + forward slash format to the native format, so this approach is portable and + easier to read. (It avoids tricky problems with having to double-escape + backslashes.) + + This is valid even on a Windows system:: + + PythonPath "['c:/path/to/project'] + sys.path" + +You can also add directives such as ``PythonAutoReload Off`` for performance. +See the `mod_python documentation`_ for a full list of options. + +Note that you should set ``PythonDebug Off`` on a production server. If you +leave ``PythonDebug On``, your users would see ugly (and revealing) Python +tracebacks if something goes wrong within mod_python. + +Restart Apache, and any request to ``/mysite/`` or below will be served by +Django. Note that Django's URLconfs won't trim the "/mysite/" -- they get passed +the full URL. + +When deploying Django sites on mod_python, you'll need to restart Apache each +time you make changes to your Python code. + +.. _mod_python documentation: http://modpython.org/live/current/doc-html/directives.html + +Multiple Django installations on the same Apache +================================================ + +It's entirely possible to run multiple Django installations on the same Apache +instance. Just use ``VirtualHost`` for that, like so:: + + NameVirtualHost * + + <VirtualHost *> + ServerName www.example.com + # ... + SetEnv DJANGO_SETTINGS_MODULE mysite.settings + </VirtualHost> + + <VirtualHost *> + ServerName www2.example.com + # ... + SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings + </VirtualHost> + +If you need to put two Django installations within the same ``VirtualHost`` +(or in different ``VirtualHost`` blocks that share the same server name), +you'll need to take a special precaution to ensure mod_python's cache doesn't +mess things up. Use the ``PythonInterpreter`` directive to give different +``<Location>`` directives separate interpreters:: + + <VirtualHost *> + ServerName www.example.com + # ... + <Location "/something"> + SetEnv DJANGO_SETTINGS_MODULE mysite.settings + PythonInterpreter mysite + </Location> + + <Location "/otherthing"> + SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings + PythonInterpreter othersite + </Location> + </VirtualHost> + +The values of ``PythonInterpreter`` don't really matter, as long as they're +different between the two ``Location`` blocks. + +Running a development server with mod_python +============================================ + +If you use mod_python for your development server, you can avoid the hassle of +having to restart the server each time you make code changes. Just set +``MaxRequestsPerChild 1`` in your ``httpd.conf`` file to force Apache to reload +everything for each request. But don't do that on a production server, or we'll +revoke your Django privileges. + +If you're the type of programmer who debugs using scattered ``print`` +statements, note that output to ``stdout`` will not appear in the Apache +log and can even `cause response errors`_. + +.. _cause response errors: http://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html + +If you have the need to print debugging information in a mod_python setup, you +have a few options. You can print to ``stderr`` explicitly, like so:: + + print >> sys.stderr, 'debug text' + sys.stderr.flush() + +(note that ``stderr`` is buffered, so calling ``flush`` is necessary if you wish +debugging information to be displayed promptly.) + +A more compact approach is to use an assertion:: + + assert False, 'debug text' + +Another alternative is to add debugging information to the template of your page. + +.. _serving-media-files: + +Serving media files +=================== + +Django doesn't serve media files itself; it leaves that job to whichever Web +server you choose. + +We recommend using a separate Web server -- i.e., one that's not also running +Django -- for serving media. Here are some good choices: + + * lighttpd_ + * Nginx_ + * TUX_ + * A stripped-down version of Apache_ + * Cherokee_ + +If, however, you have no option but to serve media files on the same Apache +``VirtualHost`` as Django, here's how you can turn off mod_python for a +particular part of the site:: + + <Location "/media"> + SetHandler None + </Location> + +Just change ``Location`` to the root URL of your media files. You can also use +``<LocationMatch>`` to match a regular expression. + +This example sets up Django at the site root but explicitly disables Django for +the ``media`` subdirectory and any URL that ends with ``.jpg``, ``.gif`` or +``.png``:: + + <Location "/"> + SetHandler python-program + PythonHandler django.core.handlers.modpython + SetEnv DJANGO_SETTINGS_MODULE mysite.settings + </Location> + + <Location "/media"> + SetHandler None + </Location> + + <LocationMatch "\.(jpg|gif|png)$"> + SetHandler None + </LocationMatch> + + +.. _lighttpd: http://www.lighttpd.net/ +.. _Nginx: http://wiki.nginx.org/Main +.. _TUX: http://en.wikipedia.org/wiki/TUX_web_server +.. _Apache: http://httpd.apache.org/ +.. _Cherokee: http://www.cherokee-project.com/ + +.. _serving-the-admin-files: + +Serving the admin files +======================= + +Note that the Django development server automagically serves admin media files, +but this is not the case when you use any other server arrangement. You're +responsible for setting up Apache, or whichever media server you're using, to +serve the admin files. + +The admin files live in (:file:`django/contrib/admin/media`) of the Django +distribution. + +Here are two recommended approaches: + + 1. Create a symbolic link to the admin media files from within your + document root. This way, all of your Django-related files -- code **and** + templates -- stay in one place, and you'll still be able to ``svn + update`` your code to get the latest admin templates, if they change. + + 2. Or, copy the admin media files so that they live within your Apache + document root. + +Using "eggs" with mod_python +============================ + +If you installed Django from a Python egg_ or are using eggs in your Django +project, some extra configuration is required. Create an extra file in your +project (or somewhere else) that contains something like the following: + +.. code-block:: python + + import os + os.environ['PYTHON_EGG_CACHE'] = '/some/directory' + +Here, ``/some/directory`` is a directory that the Apache Web server process can +write to. It will be used as the location for any unpacking of code the eggs +need to do. + +Then you have to tell mod_python to import this file before doing anything +else. This is done using the PythonImport_ directive to mod_python. You need +to ensure that you have specified the ``PythonInterpreter`` directive to +mod_python as described above__ (you need to do this even if you aren't +serving multiple installations in this case). Then add the ``PythonImport`` +line in the main server configuration (i.e., outside the ``Location`` or +``VirtualHost`` sections). For example:: + + PythonInterpreter my_django + PythonImport /path/to/my/project/file.py my_django + +Note that you can use an absolute path here (or a normal dotted import path), +as described in the `mod_python manual`_. We use an absolute path in the +above example because if any Python path modifications are required to access +your project, they will not have been done at the time the ``PythonImport`` +line is processed. + +.. _Egg: http://peak.telecommunity.com/DevCenter/PythonEggs +.. _PythonImport: http://www.modpython.org/live/current/doc-html/dir-other-pimp.html +.. _mod_python manual: PythonImport_ +__ `Multiple Django installations on the same Apache`_ + +Error handling +============== + +When you use Apache/mod_python, errors will be caught by Django -- in other +words, they won't propagate to the Apache level and won't appear in the Apache +``error_log``. + +The exception for this is if something is really wonky in your Django setup. In +that case, you'll see an "Internal Server Error" page in your browser and the +full Python traceback in your Apache ``error_log`` file. The ``error_log`` +traceback is spread over multiple lines. (Yes, this is ugly and rather hard to +read, but it's how mod_python does things.) + +If you get a segmentation fault +=============================== + +If Apache causes a segmentation fault, there are two probable causes, neither +of which has to do with Django itself. + + 1. It may be because your Python code is importing the "pyexpat" module, + which may conflict with the version embedded in Apache. For full + information, see `Expat Causing Apache Crash`_. + + 2. It may be because you're running mod_python and mod_php in the same + Apache instance, with MySQL as your database backend. In some cases, + this causes a known mod_python issue due to version conflicts in PHP and + the Python MySQL backend. There's full information in the + `mod_python FAQ entry`_. + +If you continue to have problems setting up mod_python, a good thing to do is +get a barebones mod_python site working, without the Django framework. This is +an easy way to isolate mod_python-specific problems. `Getting mod_python Working`_ +details this procedure. + +The next step should be to edit your test code and add an import of any +Django-specific code you're using -- your views, your models, your URLconf, +your RSS configuration, etc. Put these imports in your test handler function +and access your test URL in a browser. If this causes a crash, you've confirmed +it's the importing of Django code that causes the problem. Gradually reduce the +set of imports until it stops crashing, so as to find the specific module that +causes the problem. Drop down further into modules and look into their imports, +as necessary. + +.. _Expat Causing Apache Crash: http://www.dscpl.com.au/wiki/ModPython/Articles/ExpatCausingApacheCrash +.. _mod_python FAQ entry: http://modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp +.. _Getting mod_python Working: http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking + +If you get a UnicodeEncodeError +=============================== + +If you're taking advantage of the internationalization features of Django (see +:doc:`/topics/i18n/index`) and you intend to allow users to upload files, you must +ensure that the environment used to start Apache is configured to accept +non-ASCII file names. If your environment is not correctly configured, you +will trigger ``UnicodeEncodeError`` exceptions when calling functions like +``os.path()`` on filenames that contain non-ASCII characters. + +To avoid these problems, the environment used to start Apache should contain +settings analogous to the following:: + + export LANG='en_US.UTF-8' + export LC_ALL='en_US.UTF-8' + +Consult the documentation for your operating system for the appropriate syntax +and location to put these configuration items; ``/etc/apache2/envvars`` is a +common location on Unix platforms. Once you have added these statements +to your environment, restart Apache. diff --git a/parts/django/docs/howto/deployment/modwsgi.txt b/parts/django/docs/howto/deployment/modwsgi.txt new file mode 100644 index 0000000..17ba0e3 --- /dev/null +++ b/parts/django/docs/howto/deployment/modwsgi.txt @@ -0,0 +1,118 @@ +========================================== +How to use Django with Apache and mod_wsgi +========================================== + +Deploying Django with Apache_ and `mod_wsgi`_ is the recommended way to get +Django into production. + +.. _Apache: http://httpd.apache.org/ +.. _mod_wsgi: http://code.google.com/p/modwsgi/ + +mod_wsgi is an Apache module which can be used to host any Python application +which supports the `Python WSGI interface`_, including Django. Django will work +with any version of Apache which supports mod_wsgi. + +.. _python wsgi interface: http://www.python.org/dev/peps/pep-0333/ + +The `official mod_wsgi documentation`_ is fantastic; it's your source for all +the details about how to use mod_wsgi. You'll probably want to start with the +`installation and configuration documentation`_. + +.. _official mod_wsgi documentation: http://code.google.com/p/modwsgi/ +.. _installation and configuration documentation: http://code.google.com/p/modwsgi/wiki/InstallationInstructions + +Basic Configuration +=================== + +Once you've got mod_wsgi installed and activated, edit your ``httpd.conf`` file +and add:: + + WSGIScriptAlias / /path/to/mysite/apache/django.wsgi + +The first bit above is the url you want to be serving your application at (``/`` +indicates the root url), and the second is the location of a "WSGI file" -- see +below -- on your system, usually inside of your project. This tells Apache +to serve any request below the given URL using the WSGI application defined by that file. + +Next we'll need to actually create this WSGI application, so create the file +mentioned in the second part of ``WSGIScriptAlias`` and add:: + + import os + import sys + + os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' + + import django.core.handlers.wsgi + application = django.core.handlers.wsgi.WSGIHandler() + +If your project is not on your ``PYTHONPATH`` by default you can add:: + + path = '/usr/local/django' + if path not in sys.path: + sys.path.append(path) + +just above the final ``import`` line to place your project on the path. Remember to +replace 'mysite.settings' with your correct settings file, and '/usr/local/django' +with your own project's location. + +Serving media files +=================== + +Django doesn't serve media files itself; it leaves that job to whichever Web +server you choose. + +We recommend using a separate Web server -- i.e., one that's not also running +Django -- for serving media. Here are some good choices: + + * lighttpd_ + * Nginx_ + * TUX_ + * A stripped-down version of Apache_ + * Cherokee_ + +If, however, you have no option but to serve media files on the same Apache +``VirtualHost`` as Django, you can set up Apache to serve some URLs as +static media, and others using the mod_wsgi interface to Django. + +This example sets up Django at the site root, but explicitly serves ``robots.txt``, +``favicon.ico``, any CSS file, and anything in the ``/media/`` URL space as a static +file. All other URLs will be served using mod_wsgi:: + + Alias /robots.txt /usr/local/wsgi/static/robots.txt + Alias /favicon.ico /usr/local/wsgi/static/favicon.ico + + AliasMatch /([^/]*\.css) /usr/local/wsgi/static/styles/$1 + + Alias /media/ /usr/local/wsgi/static/media/ + + <Directory /usr/local/wsgi/static> + Order deny,allow + Allow from all + </Directory> + + WSGIScriptAlias / /usr/local/wsgi/scripts/django.wsgi + + <Directory /usr/local/wsgi/scripts> + Order allow,deny + Allow from all + </Directory> + +.. _lighttpd: http://www.lighttpd.net/ +.. _Nginx: http://wiki.nginx.org/Main +.. _TUX: http://en.wikipedia.org/wiki/TUX_web_server +.. _Apache: http://httpd.apache.org/ +.. _Cherokee: http://www.cherokee-project.com/ + +More details on configuring a mod_wsgi site to serve static files can be found +in the mod_wsgi documentation on `hosting static files`_. + +.. _hosting static files: http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#Hosting_Of_Static_Files + +Details +======= + +For more details, see the `mod_wsgi documentation on Django integration`_, +which explains the above in more detail, and walks through all the various +options you've got when deploying under mod_wsgi. + +.. _mod_wsgi documentation on Django integration: http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango |