Création du projet et de l'application

On choisit arbitrairement de travailler dans le dossier /home/jlesech/www-django. À chacun de l'adapter en fonction de son environnement.

On crée un projet nommé idreammicro.

django-admin.py startproject idreammicro

On se place dans le dossier du projet. Tous les chemins cités dans la suite de cet article seront relatifs à cet emplacement..

cd idreammicro

Puis on crée une application nommée helloworld.

django-admin.py startapp helloworld

Il en résulte l'arborescence suivante, introduite avec Django 1.4.

Arboresence
idreammicro
|_ helloworld
|    |_ __init__.py
|    |_ models.py
|    |_ tests.py
|    |_ views.py
|_ idreammicro
|    |_ __init.py__
|    |_ settings.py
|    |_ urls.py
|    |_ wsgi.py
|_ manage.py

Support WSGI

Django 1.4 a introduit une amélioration du support WSGI, en embarquant une application WSGI dans le fichier idreammicro/wsgi.py.

idreammicro/wsgi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"""
WSGI config for idreammicro project.
 
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
 
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
 
"""
import os
 
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "idreammicro.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "idreammicro.settings")
 
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
 
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)

Activation de l'application

Dans le fichier idreammicro/settings.py, on active l'application helloworld (ligne 127).

idreammicro/settings.py
116
117
118
119
120
121
122
123
124
125
126
127
128
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'helloworld',
)

Vue

Dans le fichier helloworld/views.py, on crée la vue index.

helloworld/views.py
1
2
3
4
from django.http import HttpResponse
 
def index(request):
    return HttpResponse("Hello world!")

Celle-ci se veut la plus simple possible et affiche un simple Hello world!.

Urls

On crée le fichier helloworld/urls.py, on configure l'url de la vue index précédemment créée.

helloworld/urls.py
1
2
3
4
5
6
7
from django.conf.urls import patterns, url
 
from helloworld import views
 
urlpatterns = patterns('',
    url(r'^$', views.index, name='index')
)

Dans le fichier idreammicro/urls.py, on inclut le fichier contenant les urls de l'application helloworld.

idreammicro/urls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from django.conf.urls import patterns, include, url
 
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
 
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'idreammicro.views.home', name='home'),
    # url(r'^idreammicro/', include('idreammicro.foo.urls')),
 
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
 
    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
     
    url(r'^helloworld/', include('helloworld.urls')),
)

Afin de vérifier que le projet et l'application sont fonctionnels, on lance le serveur de développement.

python manage.py runserver

Dans un navigateur, on saisit l'adresse http://localhost:8000/helloworld.

helloworld.png

Magnifique ! Le projet et l'application fonctionnent. On peut maintenant passer aux choses sérieuses et les servir à l'aide d'Apache.

Virtual Host Apache

On choisit de créer un serveur virtuel dédié au projet Django. Les opérations suivantes nécessitent d'avoir les droits d'administration.

On crée le fichier /etc/apache2/sites-available/idreammicro.

Serveur virtuel idreammicro
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<VirtualHost *:80>
 
    ServerName django
    ServerAlias django
 
    DocumentRoot /home/jlesech/www-django/idreammicro
 
    <Directory /home/jlesech/www-django/idreammicro>
        Order allow,deny
        Allow from all
    </Directory>
 
    WSGIDaemonProcess django processes=2 threads=15 display-name=%{GROUP} python-path=/home/jlesech/www-django/idreammicro
    WSGIProcessGroup django
 
    WSGIScriptAlias / /home/jlesech/www-django/idreammicro/idreammicro/wsgi.py
 
    <Directory /home/jlesech/www-django/idreammicro/idreammicro>
        Order allow,deny
        Allow from all
    </Directory>
 
    ErrorLog ${APACHE_LOG_DIR}/idreammicro_error.log
 
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
     
    CustomLog ${APACHE_LOG_DIR}/idreammicro_access.log combined
 
</VirtualHost>

On active le nouveau serveur virtuel.

a2ensite idreammicro

Dans le fichier /etc/hosts, on ajoute un host (ligne 3).

1
2
3
4
5
6
7
8
9
10
127.0.0.1   localhost
127.0.1.1   i7
127.0.0.1   django
 
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Dans un navigateur, on saisit l'adresse http://django/helloworld.

helloworld2.png

Conclusion

Comme l'avait montré le précédent article, servir un projet Django avec Apache et le module WSGI était déjà relativement simple. C'est encore plus simple aujourd'hui !

Par rapport à Django 1.3, Django 1.4 et ses versions supérieures nous épargnent la création de l'application WSGI. Ainsi on se concentre sur la partie spécifique à chaque serveur, en l'occurrence la création d'un serveur virtuel Apache dédié au projet Django.

Références

Sujets relatifs