Project Development
Version 84 (Paul Carensac, 03/31/2016 10:44 am) → Version 85/177 (Paul Carensac, 03/31/2016 10:47 am)
h1. Project Development
Project Installation page : [[Project Installation]]
HOWTO Format Redmine Wiki : http://www.redmine.org/projects/redmine/wiki/FrRedmineWikiFormatting
Project's applications : [[Pyros applications]]
{{>toc}}
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}TODO%
cf Roadmap
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}LIENS UTILES%
* pyrossu : pyrossu!
* readonly admin interface : https://gist.github.com/aaugustin/1388243
* Liens vers web local :
* homepage: http://localhost:8000
* admin: http://localhost:8000/admin
* Eclipse:
* Shift-Ctrl-f (ou Shift-Cmd-f) : reformatage du fichier selon PEP8
* Shift-Ctrl-1 : make doc string ...
* Django:
* Un répertoire de modules : https://www.djangopackages.com/
* Extensions
* *django_jenkins* : intégration à Jenkins
* *factory_boy* : création de grappes de données pour les tests
* https://factoryboy.readthedocs.org/en/latest/introduction.html
* https://factoryboy.readthedocs.org/en/latest/orms.html
* Modules très utilisés:
* django_linaration_pagination : affichage de listes paginées
* django_sorting : affichage de tableaux triables
* django_breadcrumbs : création de fil d'ariane
* django_xworkflows : gestion de workflows
* easy_thumbnails : gestion de miniatures pour les images
* Coding style: https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style
* Doc : *https://docs.djangoproject.com/fr (EN FRANCAIS)*
* https://docs.djangoproject.com (EN)
* http://www.django-fr.org/planete
* https://docs.djangoproject.com/en/1.9/howto/deployment
* test fixtures : https://docs.djangoproject.com/en/1.9/howto/initial-data/
* managing static files: https://docs.djangoproject.com/en/1.9/howto/static-files/
* deploying static files: https://docs.djangoproject.com/en/1.9/howto/static-files/deployment/
* install on Windows: https://docs.djangoproject.com/en/1.9/howto/windows/
* writing migrations: https://docs.djangoproject.com/en/1.9/howto/writing-migrations/
* migrations : https://docs.djangoproject.com/en/1.9/topics/migrations/
* Django settings: https://docs.djangoproject.com/en/1.9/topics/settings/
* Testing: https://docs.djangoproject.com/en/1.9/topics/testing/
* User authentication: https://docs.djangoproject.com/en/1.9/topics/auth/
* Autres ressources:
* django-admin command: https://docs.djangoproject.com/en/1.9/ref/django-admin
* http://stackoverflow.com/questions/tagged/django
* https://www.djangopackages.com/
* http://forum.django-fr.org
* La mailing list : django@lists.afpy.org
* Image processing with Python : https://pillow.readthedocs.org/en/latest/handbook/overview.html
* Git docs:
* Permissions gitlab: https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/permissions/permissions.md
* https://git-scm.com/docs
* https://git-scm.com/book/fr/v1/Les-bases-de-Git-Travailler-avec-des-d%C3%A9p%C3%B4ts-distants
* les workflows: https://aresu.dsi.cnrs.fr/spip.php?article219
* Git for Eclipse users : http://wiki.eclipse.org/EGit/Git_For_Eclipse_Users
* Git sur sourcesup (avec jenkins) : https://services.renater.fr/sourcesup/formation/chap04#gestion_d_un_projet_avec_git_jenkins_sonar_et_nexus
* CADOR web interface: http://cador.obs-hp.fr/ros/manual/cador_actions.html
* pylint (analyse de code) : https://www.pylint.org
* pyreverse (uml diagrams generation, inclus dans pylint) : https://www.logilab.org/blogentry/6883
* tox (a generic virtualenv management and test command line tool) : https://testrun.org/tox/latest/index.html
---
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}I - DATABASE SCHEMA (v0.2.1)%
{{thumbnail(PYROS_PDM_v021.png, size=300, title=Pyros data model)}}
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}II - Get the project (from gitlab)%
h3. Gitlab management interface
https://gitlab.irap.omp.eu/epallier/pyros
https://gitlab.irap.omp.eu/epallier/pyros/team
h3. Get the project
https://projects.irap.omp.eu/projects/pyros/wiki/Project_Installation#II-Get-the-project-from-gitlab
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}III - INSTALLATION%
https://projects.irap.omp.eu/projects/pyros/wiki/Project_Installation#III-INSTALLATION
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}IV - CONFIGURATION of the Django Back Office (administration interface)%
[[django_backoffice_config|Configuration of the Django Back office (admin)]]
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}V - EVOLUTION OF THE PROJECT%
h3. Linking the User model to the django's one
* Modifications in models.py :
* Rename User model to PyrosUser
* Rename user table name to pyros_user
* Change all occurences (User -> PyrosUser, users -> pyros_users, ...)
* from django.contrib.auth.models import User <== add at the beginning of the file
* user = models.OneToOneField(User, on_delete=models.CASCADE) <== add this field in PyrosUser declaration
* delete fields in PyrosUser : name, firstname, email, login, pass
* Modifications in admin.py :
* Change all occurences (User* -> PyrosUser*, users -> pyros_users, ...)
<pre>
$ python manage.py makemigrations pyrosapp
$ python manage.py migrate
</pre>
---
h3. Manage static files (for admin but also for each application)
./manage.py runserver
if DEBUG=False, we have errors, missing static files :
<pre>
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/login.css
Not Found: /admin/login
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/login.css
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/login.css
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/dashboard.css
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/base.css
…
</pre>
=> We have to activate the static files management
(see https://docs.djangoproject.com/en/1.9/howto/static-files)
In pyros/urls.py, add this:
<pre>
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</pre>
STATIC_ROOT must be defined in settings and says where is the root of all static files
Edit settings.py, add:
<pre>
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'public', 'static')
</pre>
./manage.py collectstatic
=> 56 static files copied to '.../PYROS/public/static'
(in fact it is in public/static/admin/)
Cette commande copie tous les fichiers statiques de toutes les applis
dans public/static
Apache viendra lire ce dossier unique
A chq changement d’un fichier statique d’une appli, exécuter « collectstatic » pour mettre à jour le dossier final public/static (auquel on ne doit pas toucher manuellement, c’est un dossier « final »)
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}DJANGO SHELL (top cool)%
cf page 60 for the ORM methods
<pre>
./manage.py shell
Python 3.5.1 (default, Mar 2 2016, 03:38:02)
(InteractiveConsole)
>>> import django
>>> from pyrosapp.models import *
>>> country = Country(name='mexico', quota=1)
>>> country.save()
(ajout si pas d’id, modif si id)
>>> country = Country(name='france')
>>> country.save()
>>> country.pk
>>> 2
>>> countries = Country.objects.all()
>>> countries.count
>>> <bound method QuerySet.count of <Country: mexico>, <Country: france>>
>>> countries.count()
>>> 2
>>> print(countries)
>>> <Country: mexico>, <Country: france>
>>> print(countries.query)
>>> SELECT country.id, country.name, country.desc, country.quota FROM country
>>> cs = countries.filter(name__icontains='fran')
>>> print(cs)
>>> <Country: france>
>>> cs = countries.filter(name__startswith='me')
>>> print(cs)
>>> <Country: mexico>
</pre>
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}HOWTO (divers)%
h3. Models
1) Relationships between models (1-1, 1-N, N-M) (p55)
models.ManyToManyField : représente une relation de type N-N
(peu importe de quel côté on le déclare)
models.OneToOneField : attention, le sens est important, on n’accèdera d’une table à l’autre que dans un sens
task <=> user
task.user
user.task_set
2) Quelques options pour les champs
Chaque type de champ possède ses propres propriétés. Cependant, certaines sont communes et souvent utilisées comme :
verbose_name: label du champ
null : valeur NULL autorisée ou non en base de données
blank : valeur vide autorisée lors de la validation du champ dans un formulaire
default : valeur par défaut pour une nouvelle instance
editable : le champ doit-il apparaître automatiquement dans les formulaires
...
h3. Pour relier une appli python pure à un projet django :
=> Ajouter le src/ dans le pythonpath
h3. Séparer le code métier :
=> installer le code métier comme un module via pip
Couches :
* présentation
* métier
* modèle
h3. ORM
(cf page 60)
<pre>
b = Book(name='Two scoops of django',
release=date(2013, 08, 31))
b.save()
=> ajout car pas d’id,
b.name ='Two scoops of django - Best practices'
b.save()
=> modif car il y a un id
b.delete()
Toutes les instances:
Book.objects.all()
Liste filtrée:
books = Book.objects.filter(
release__gte=date(2013, 01, 01)
).exclude(
borrowed=True
)
A! La requete est exécutée le plus tard possible, seulement quand django a vraiment besoin de l’exécuter
Liste ordonnée:
books = Book.objects.exclude(borrowed=True).order_by('title')
print (books.author)
Une instance précise:
Book.objects.get(pk=12)
</pre>
Liens vers objets associés:
Retrouver les livres disponibles d'un auteur :
>> author = Author.objects.get(pk=25)
>> author.books.filter(borrowed=False)
(books est le related name déclaré dans la relation manytomany)
Ajouter un livre à une catégorie :
>> category = Category.objects.get(pk=5)
>> book = Book.objects.get(pk=12)
>> category.books.add(book)
Supprimer l'association de livres à une catégorie :
>> category = Category.objects.get(pk=5)
>> category.books.clear()
---
h3. Serveur Web
Apache : gère tous les fichiers statiques (images, html…), et délègue les fichiers python au serveur django
Moteur web django sera soit du wsgi soit du unicorn
Par défaut, 1 seul worker, mais on peut en configurer plusieurs,
l’idéal étant de faire nb coeurs + 1 (le worker maître qui fait le dispatching aux autres)
Frontend : Apache ou Ngininx
Backend : gunicorn (gère facilement des workers) ou uwsgi
==> gunicorn library.wsgi
(à la place de manage runserver ==> A EVITER EN PROD)
pip install gunicorn
gunicorn library.wsgi
ou
gunicorn - - workers 5 library.wsgi
(gunicorn == tomcat, serveur d’appli Python)
1) URL arrive à Apache, qui dispatche (il gère seul les fichiers statiques, et les fichiers python il les transmet à Django)
2) le fichier library/urls.py prend le relai pour tout ce qui est django
*On peut ajouter un fichier urls.py pour gérer les urls de l’appli
(on garde le urls.py général du projet pour gérer les grandes urls):*
<pre>
Déclaration d'une URL
# books/urls.py
from django.conf.urls import patterns, include, url
urlpatterns = [
url(r'^book_list$', 'books.views.book_list', name='book_list'),
]
Inclusion des URLs de l'application au projet
# library/urls.py
...
urlpatterns = [
...
url(r'^books/', include('books.urls', namespace='books')),
]
</pre>
h3. MTV design pattern
MTV == MVC :
Model = Model
Template = View
View = Controller
CREATION DE LA VUE (en fait, le controleur) : slide 23
views.py = CONTROLEUR
Template = LA VUE (slide 24)
(on peut user Jinja à la place du moteur django par défaut)
Dans chq appli, on crée un dossier templates/ et un sous-dossier du nom de l’appli/
(==> todo/templates/todo/)
Même principe pour les fichiers statiques :
src/static/appli1, appli2, appli3…
NOMENCLATURE template :
nommodèle_action.html
(ex: book_list.html)
*On pourrait tout mettre dans le urls.py du projet, MAIS c’est mieux
de créer un fichier urls.py PAR APPLI, puis de les inclure dans le fichier urls.py principal*
Class-based views ==> classes controleurs
Les méthodes get() et post() sont déjà définies, et on peut les surcharger…
Avec un template (gabarit), on peut générer autre chose que du html,
on peut par ex générer du texte, du pdf, un email, un xml…
Vue liste (et détail) :
https://docs.djangoproject.com/fr/1.8/topics/class-based-views/generic-display/
1) todo/views.py
from django.views.generic import ListView
from books.models import Publisher
class PublisherList(ListView):
model = Publisher
2) todolist/urls.py
from django.conf.urls import url
from books.views import PublisherList
urlpatterns = [
url(r'^publishers/$', PublisherList.as_view()),
]
3) todo/templates/todo/
- Vue Liste : par défaut le template reçoit un objet « objects_list »
- Vue détail : object (on peut faire object.pk, …)
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}INSTALLATION FROM THE BEGINNING (for dev only, history of the initial project creation)%
[[pyros_install_from_start|Pyros installation from the beginning]]
Project Installation page : [[Project Installation]]
HOWTO Format Redmine Wiki : http://www.redmine.org/projects/redmine/wiki/FrRedmineWikiFormatting
Project's applications : [[Pyros applications]]
{{>toc}}
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}TODO%
cf Roadmap
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}LIENS UTILES%
* pyrossu : pyrossu!
* readonly admin interface : https://gist.github.com/aaugustin/1388243
* Liens vers web local :
* homepage: http://localhost:8000
* admin: http://localhost:8000/admin
* Eclipse:
* Shift-Ctrl-f (ou Shift-Cmd-f) : reformatage du fichier selon PEP8
* Shift-Ctrl-1 : make doc string ...
* Django:
* Un répertoire de modules : https://www.djangopackages.com/
* Extensions
* *django_jenkins* : intégration à Jenkins
* *factory_boy* : création de grappes de données pour les tests
* https://factoryboy.readthedocs.org/en/latest/introduction.html
* https://factoryboy.readthedocs.org/en/latest/orms.html
* Modules très utilisés:
* django_linaration_pagination : affichage de listes paginées
* django_sorting : affichage de tableaux triables
* django_breadcrumbs : création de fil d'ariane
* django_xworkflows : gestion de workflows
* easy_thumbnails : gestion de miniatures pour les images
* Coding style: https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style
* Doc : *https://docs.djangoproject.com/fr (EN FRANCAIS)*
* https://docs.djangoproject.com (EN)
* http://www.django-fr.org/planete
* https://docs.djangoproject.com/en/1.9/howto/deployment
* test fixtures : https://docs.djangoproject.com/en/1.9/howto/initial-data/
* managing static files: https://docs.djangoproject.com/en/1.9/howto/static-files/
* deploying static files: https://docs.djangoproject.com/en/1.9/howto/static-files/deployment/
* install on Windows: https://docs.djangoproject.com/en/1.9/howto/windows/
* writing migrations: https://docs.djangoproject.com/en/1.9/howto/writing-migrations/
* migrations : https://docs.djangoproject.com/en/1.9/topics/migrations/
* Django settings: https://docs.djangoproject.com/en/1.9/topics/settings/
* Testing: https://docs.djangoproject.com/en/1.9/topics/testing/
* User authentication: https://docs.djangoproject.com/en/1.9/topics/auth/
* Autres ressources:
* django-admin command: https://docs.djangoproject.com/en/1.9/ref/django-admin
* http://stackoverflow.com/questions/tagged/django
* https://www.djangopackages.com/
* http://forum.django-fr.org
* La mailing list : django@lists.afpy.org
* Image processing with Python : https://pillow.readthedocs.org/en/latest/handbook/overview.html
* Git docs:
* Permissions gitlab: https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/permissions/permissions.md
* https://git-scm.com/docs
* https://git-scm.com/book/fr/v1/Les-bases-de-Git-Travailler-avec-des-d%C3%A9p%C3%B4ts-distants
* les workflows: https://aresu.dsi.cnrs.fr/spip.php?article219
* Git for Eclipse users : http://wiki.eclipse.org/EGit/Git_For_Eclipse_Users
* Git sur sourcesup (avec jenkins) : https://services.renater.fr/sourcesup/formation/chap04#gestion_d_un_projet_avec_git_jenkins_sonar_et_nexus
* CADOR web interface: http://cador.obs-hp.fr/ros/manual/cador_actions.html
* pylint (analyse de code) : https://www.pylint.org
* pyreverse (uml diagrams generation, inclus dans pylint) : https://www.logilab.org/blogentry/6883
* tox (a generic virtualenv management and test command line tool) : https://testrun.org/tox/latest/index.html
---
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}I - DATABASE SCHEMA (v0.2.1)%
{{thumbnail(PYROS_PDM_v021.png, size=300, title=Pyros data model)}}
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}II - Get the project (from gitlab)%
h3. Gitlab management interface
https://gitlab.irap.omp.eu/epallier/pyros
https://gitlab.irap.omp.eu/epallier/pyros/team
h3. Get the project
https://projects.irap.omp.eu/projects/pyros/wiki/Project_Installation#II-Get-the-project-from-gitlab
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}III - INSTALLATION%
https://projects.irap.omp.eu/projects/pyros/wiki/Project_Installation#III-INSTALLATION
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}IV - CONFIGURATION of the Django Back Office (administration interface)%
[[django_backoffice_config|Configuration of the Django Back office (admin)]]
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}V - EVOLUTION OF THE PROJECT%
h3. Linking the User model to the django's one
* Modifications in models.py :
* Rename User model to PyrosUser
* Rename user table name to pyros_user
* Change all occurences (User -> PyrosUser, users -> pyros_users, ...)
* from django.contrib.auth.models import User <== add at the beginning of the file
* user = models.OneToOneField(User, on_delete=models.CASCADE) <== add this field in PyrosUser declaration
* delete fields in PyrosUser : name, firstname, email, login, pass
* Modifications in admin.py :
* Change all occurences (User* -> PyrosUser*, users -> pyros_users, ...)
<pre>
$ python manage.py makemigrations pyrosapp
$ python manage.py migrate
</pre>
---
h3. Manage static files (for admin but also for each application)
./manage.py runserver
if DEBUG=False, we have errors, missing static files :
<pre>
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/login.css
Not Found: /admin/login
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/login.css
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/login.css
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/dashboard.css
Not Found: /static/admin/css/base.css
Not Found: /static/admin/css/base.css
…
</pre>
=> We have to activate the static files management
(see https://docs.djangoproject.com/en/1.9/howto/static-files)
In pyros/urls.py, add this:
<pre>
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</pre>
STATIC_ROOT must be defined in settings and says where is the root of all static files
Edit settings.py, add:
<pre>
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'public', 'static')
</pre>
./manage.py collectstatic
=> 56 static files copied to '.../PYROS/public/static'
(in fact it is in public/static/admin/)
Cette commande copie tous les fichiers statiques de toutes les applis
dans public/static
Apache viendra lire ce dossier unique
A chq changement d’un fichier statique d’une appli, exécuter « collectstatic » pour mettre à jour le dossier final public/static (auquel on ne doit pas toucher manuellement, c’est un dossier « final »)
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}DJANGO SHELL (top cool)%
cf page 60 for the ORM methods
<pre>
./manage.py shell
Python 3.5.1 (default, Mar 2 2016, 03:38:02)
(InteractiveConsole)
>>> import django
>>> from pyrosapp.models import *
>>> country = Country(name='mexico', quota=1)
>>> country.save()
(ajout si pas d’id, modif si id)
>>> country = Country(name='france')
>>> country.save()
>>> country.pk
>>> 2
>>> countries = Country.objects.all()
>>> countries.count
>>> <bound method QuerySet.count of <Country: mexico>, <Country: france>>
>>> countries.count()
>>> 2
>>> print(countries)
>>> <Country: mexico>, <Country: france>
>>> print(countries.query)
>>> SELECT country.id, country.name, country.desc, country.quota FROM country
>>> cs = countries.filter(name__icontains='fran')
>>> print(cs)
>>> <Country: france>
>>> cs = countries.filter(name__startswith='me')
>>> print(cs)
>>> <Country: mexico>
</pre>
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}HOWTO (divers)%
h3. Models
1) Relationships between models (1-1, 1-N, N-M) (p55)
models.ManyToManyField : représente une relation de type N-N
(peu importe de quel côté on le déclare)
models.OneToOneField : attention, le sens est important, on n’accèdera d’une table à l’autre que dans un sens
task <=> user
task.user
user.task_set
2) Quelques options pour les champs
Chaque type de champ possède ses propres propriétés. Cependant, certaines sont communes et souvent utilisées comme :
verbose_name: label du champ
null : valeur NULL autorisée ou non en base de données
blank : valeur vide autorisée lors de la validation du champ dans un formulaire
default : valeur par défaut pour une nouvelle instance
editable : le champ doit-il apparaître automatiquement dans les formulaires
...
h3. Pour relier une appli python pure à un projet django :
=> Ajouter le src/ dans le pythonpath
h3. Séparer le code métier :
=> installer le code métier comme un module via pip
Couches :
* présentation
* métier
* modèle
h3. ORM
(cf page 60)
<pre>
b = Book(name='Two scoops of django',
release=date(2013, 08, 31))
b.save()
=> ajout car pas d’id,
b.name ='Two scoops of django - Best practices'
b.save()
=> modif car il y a un id
b.delete()
Toutes les instances:
Book.objects.all()
Liste filtrée:
books = Book.objects.filter(
release__gte=date(2013, 01, 01)
).exclude(
borrowed=True
)
A! La requete est exécutée le plus tard possible, seulement quand django a vraiment besoin de l’exécuter
Liste ordonnée:
books = Book.objects.exclude(borrowed=True).order_by('title')
print (books.author)
Une instance précise:
Book.objects.get(pk=12)
</pre>
Liens vers objets associés:
Retrouver les livres disponibles d'un auteur :
>> author = Author.objects.get(pk=25)
>> author.books.filter(borrowed=False)
(books est le related name déclaré dans la relation manytomany)
Ajouter un livre à une catégorie :
>> category = Category.objects.get(pk=5)
>> book = Book.objects.get(pk=12)
>> category.books.add(book)
Supprimer l'association de livres à une catégorie :
>> category = Category.objects.get(pk=5)
>> category.books.clear()
---
h3. Serveur Web
Apache : gère tous les fichiers statiques (images, html…), et délègue les fichiers python au serveur django
Moteur web django sera soit du wsgi soit du unicorn
Par défaut, 1 seul worker, mais on peut en configurer plusieurs,
l’idéal étant de faire nb coeurs + 1 (le worker maître qui fait le dispatching aux autres)
Frontend : Apache ou Ngininx
Backend : gunicorn (gère facilement des workers) ou uwsgi
==> gunicorn library.wsgi
(à la place de manage runserver ==> A EVITER EN PROD)
pip install gunicorn
gunicorn library.wsgi
ou
gunicorn - - workers 5 library.wsgi
(gunicorn == tomcat, serveur d’appli Python)
1) URL arrive à Apache, qui dispatche (il gère seul les fichiers statiques, et les fichiers python il les transmet à Django)
2) le fichier library/urls.py prend le relai pour tout ce qui est django
*On peut ajouter un fichier urls.py pour gérer les urls de l’appli
(on garde le urls.py général du projet pour gérer les grandes urls):*
<pre>
Déclaration d'une URL
# books/urls.py
from django.conf.urls import patterns, include, url
urlpatterns = [
url(r'^book_list$', 'books.views.book_list', name='book_list'),
]
Inclusion des URLs de l'application au projet
# library/urls.py
...
urlpatterns = [
...
url(r'^books/', include('books.urls', namespace='books')),
]
</pre>
h3. MTV design pattern
MTV == MVC :
Model = Model
Template = View
View = Controller
CREATION DE LA VUE (en fait, le controleur) : slide 23
views.py = CONTROLEUR
Template = LA VUE (slide 24)
(on peut user Jinja à la place du moteur django par défaut)
Dans chq appli, on crée un dossier templates/ et un sous-dossier du nom de l’appli/
(==> todo/templates/todo/)
Même principe pour les fichiers statiques :
src/static/appli1, appli2, appli3…
NOMENCLATURE template :
nommodèle_action.html
(ex: book_list.html)
*On pourrait tout mettre dans le urls.py du projet, MAIS c’est mieux
de créer un fichier urls.py PAR APPLI, puis de les inclure dans le fichier urls.py principal*
Class-based views ==> classes controleurs
Les méthodes get() et post() sont déjà définies, et on peut les surcharger…
Avec un template (gabarit), on peut générer autre chose que du html,
on peut par ex générer du texte, du pdf, un email, un xml…
Vue liste (et détail) :
https://docs.djangoproject.com/fr/1.8/topics/class-based-views/generic-display/
1) todo/views.py
from django.views.generic import ListView
from books.models import Publisher
class PublisherList(ListView):
model = Publisher
2) todolist/urls.py
from django.conf.urls import url
from books.views import PublisherList
urlpatterns = [
url(r'^publishers/$', PublisherList.as_view()),
]
3) todo/templates/todo/
- Vue Liste : par défaut le template reçoit un objet « objects_list »
- Vue détail : object (on peut faire object.pk, …)
---
h2. %{margin-left:0px; font-weight:bold; font-size:25px; display:block; color:red;}INSTALLATION FROM THE BEGINNING (for dev only, history of the initial project creation)%
[[pyros_install_from_start|Pyros installation from the beginning]]