logo Debian Debian Debian-France Debian-Facile Debian-fr.org Forum-Debian.fr Debian ? Communautés logo inclusivité

Debian-facile

Bienvenue sur Debian-Facile, site d'aide pour les nouveaux utilisateurs de Debian.

Vous n'êtes pas identifié(e).


L'icône rouge permet de télécharger chaque page du wiki visitée au format PDF et la grise au format ODT → ODT PDF Export

Développer en Python3 avec Django

  • Objet : Installer un environnement virtuel pour coder en python3 avec Django
  • Niveau requis :

Installations

Installer les outils et bibliothèques pour développer en python ou python3

Sur Jessie, python et python 3 sont tous deux installés.
  • Fichiers d'en-tête de Python
apt-get install python-dev python3-dev
  • Pour l'algèbre avec scipy
apt-get install libblas3 libblas-dev liblapack3 liblapack-dev
  • Bibliothèques FreeType nécessaire par matplotlib
apt-get install libfreetype6 libfreetype6-dev
  • Dépendances nécessaire pour la cryptographie
apt-get install libffi-dev libssl-dev
  • Les paquets Core Python
apt-get install python-pip python3-pip
apt-get install python-virtualenv
À savoir sur Jessie, il est inutile de lancer :

apt-get install python3-virtualenv

En effet, avec la commande apt-get install python-virtualenv a installé python3-virtualenv et python-virtualenv

  1. python3-pip (ou python-pip) : installateur de paquets python, Pip permet d'installer aisément des modules Python, à la manière dont on installe des paquets dans une distribution linux;
  2. python3-dev (ou python-dev ): permet d'utiliser des outils de développement pour la construction des modules Python, non pris en charge par pip, en particulier pour utiliser des bibliothèques avec des extensions en C
  3. virtualenv : permet de créer un environnement cloisonné Python
  • Installer la documentation python
apt-get install python-doc python3-doc
  • pour utiliser pyenv
apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \
libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev
  • Sans rapport avec le développement mais utilisé plus bas
apt-get install tree

Vim IDE pour coder pour python3

Créer des projets Django en python2 ou python3

Les versions de python sur sa Jessie

 ls /usr/bin/python*
/usr/bin/python            /usr/bin/python3            /usr/bin/python3-config
/usr/bin/python2           /usr/bin/python3.4          /usr/bin/python3m
/usr/bin/python2.7         /usr/bin/python3.4-config   /usr/bin/python3m-config
/usr/bin/python2.7-config  /usr/bin/python3.4m         /usr/bin/python-config
/usr/bin/python2-config    /usr/bin/python3.4m-config

Problème avec python pour utiliser virtualenv

L'idée suivie ici est de pouvoir aussi bien créer des projets Django pour dans la version 2 que la version 3 de python.

Pour ce faire, on va créer un environnement virtuel dans un dossier créé dans le répertoire courant de l'utilisateur du système. On pourra alors installer Django aussi bien pour y coder en python2 qu'en python3, sans se soucier de la version mise en place sur l'ensemble du système.

Cela évitera aussi de se mélanger les pinceaux entre les utilitaires pip install … ou pip3 install ….

On n'utilisera pas virtualenv seul, mais on l'utilisera avec pyenv afin de s'éviter quelque conflits lors de l'installation de django.

En effet :

python --version
Python 3.4.2
virtualenv MonPy3Django -p /usr/bin/python3.4
cd MonPy3Django/
source bin/activate 1.8-3.4
Downloading/unpacking django
  Downloading Django-1.9-py2.py3-none-any.whl (6.6MB): 6.6MB downloaded
Installing collected packages: django
*** Error compiling '/tmp/pip-build-c20d1nfa/django/django/conf/app_template/apps.py'...
  File "/tmp/pip-build-c20d1nfa/django/django/conf/app_template/apps.py", line 4
    class {{ camel_case_app_name }}Config(AppConfig):
          ^
SyntaxError: invalid syntax
 
*** Error compiling '/tmp/pip-build-c20d1nfa/django/django/conf/app_template/models.py'...
  File "/tmp/pip-build-c20d1nfa/django/django/conf/app_template/models.py", line 1
    {{ unicode_literals }}from django.db import models
                             ^
SyntaxError: invalid syntax
 
Successfully installed django
Cleaning up...

:-/

rm -r ~/MonPy3Django

Installer pyenv

git clone https://github.com/yyuu/pyenv.git ~/.pyenv
  • On configure le PATH en ajoutant quelques lignes au fichier ~/.bashrc
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
  • On recharge son shell
exec $SHELL
  • On installe les versions de python que l'on voudra utiliser dans différents projets
pyenv install 2.7.9
pyenv install 3.4.3
L'exécution des deux commandes précédentes est longue. Patience…
pyenv versions
* system (set by /home/hypathie/.pyenv/version)
  2.7.9
  3.4.3

Quelques commandes pyenv

  • Avoir une liste des commandes pyenv
pyenv
Some useful pyenv commands are:
   commands    List all available pyenv commands
   local       Set or show the local application-specific Python version
   global      Set or show the global Python version
   shell       Set or show the shell-specific Python version
   install     Install a Python version using python-build
   uninstall   Uninstall a specific Python version
   rehash      Rehash pyenv shims (run this after installing executables)
   version     Show the current Python version and its origin
   versions    List all Python versions available to pyenv
   which       Display the full path to an executable
   whence      List all Python versions that contain the given executable
  • Comment lancer une commande pyenv
pyenv +lacommande
  • Pour coder dans une version de python, on appelle le shell de pyenv de la version souhaitée

- Pour utiliser la version 2 (installée plutôt)

pyenv shell 2.7.9

- Pour savoir quelle est la version de son shell

pyenv shell
2.7.9

- version de python utilisée

python --version
Python 2.7.9

- Depuis où ?

 which python
/home/hypathie/.pyenv/shims/python

- Pour utiliser la version 3 (installée aussi plutôt)

pyenv shell 3.4.3
python --version
Python 3.4.3

Utiliser virtualenv avec pyenv

  • Configuration du système pour utiliser virtualenv avec pyenv
git clone https://github.com/yyuu/pyenv-virtualenv.git ~/.pyenv/plugins/pyenv-virtualenv
echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc
exec $SHELL
  • Créer un répertoire où l'on pourra installer django pour python 3
mkdir ProjetsDjangoPy3 && cd ProjetsDjangoPy3
pyenv shell 3.4.3
python --version
Python 3.4.3
pyenv virtualenv 1.8-3.4
Ignoring indexes: https://pypi.python.org/simple
Requirement already satisfied (use --upgrade to upgrade): setuptools in /home/hypathie/.pyenv/versions/3.4.3/envs/1.8-3.4/lib/python3.4/site-packages
Requirement already satisfied (use --upgrade to upgrade): pip in /home/hypathie/.pyenv/versions/3.4.3/envs/1.8-3.4/lib/python3.4/site-packages
pyenv activate 1.8-3.4

Installer Django

  • On vérifie qu'on est dans le répertoire de l'environnement préparé plus haut
pwd
/home/hypathie/ProjetsDjangoPy3
  • On installe Django
pip install django
You are using pip version 6.0.8, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting django
  Downloading Django-1.9-py2.py3-none-any.whl (6.6MB)
    100% |################################| 6.6MB 88kB/s 
Installing collected packages: django
 
Successfully installed django-1.9
(1.8-3.4) hypathie@debian:~/MonPython3Django$ pip install django

Pas d'erreur cette fois 8-)

  • Pour vérifier les versions
django-admin.py --version
1.9
python --version
Python 3.4.3

Avec la commande recommandée par la doc officielle de django:

python3 -c "import django; print(django.get_version())"

on a aussi :

1.9

8-)

  • Pour sortir de pyenv :
pyenv deactivate

Créer un projet django sous python 3

Si l'on reprend le wiki ici !
  • On va dans son répertoire configuré pour python 3 dans lequel est installé django
cd ~/ProjetsDjangoPy3/
  • On active pyenv
pyenv activate 1.8-3.4

Le prompt de terminal a changé, il devient quelque chose comme cela :

(1.8-3.4) hypathie@debian:~/ProjetsDjangoPy3/premierProjet$
  • Pour créer le projet Django nommé par exemple “premierProjet”
django-admin.py startproject premierProjet
tree
.
└── premierProjet
    ├── manage.py
    └── premierProjet
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py
Et voilà, partir de là, on retombe sur nos pattes

On peut suivre simplement le premier projet de la doc officielle de Django et les commandes qu'elle indique alors que notre environnement virtuel est sous python 3 !
https://docs.djangoproject.com/fr/1.8/intro/tutorial01/

  • A chaque fois que l'on veut reprendre l'avancement de son projet

On se place dans le projet Django (répertoire premierProjet et non dans son sous-répertoire de même nom !)

cd ~/ProjetsDjangoPy3/premierProjet/
  • On active pyenv pour utiliser l'interpréteur python
pyenv activate 1.8-3.4
  • Pour tester
python manage.py runserver

ou celle-ci 8-)

python3 manage.py runserver

Et on obtient :


  • Pour arrêter le serveur :
ctrl+c
  • Pour sortir de l'interpréteur python du shell pyenv
pyenv deactivate

Résumer des fichiers de configuration et commandes "manage.py"

Le fichier ''settings.py'' : pour associer une BDD au projet

  • On peut aller voir dans le sous-répertoire premierProjet
cd ~/ProjetsDjangoPy3/premierProjet/premierProjet
ls
__init__.py  __pycache__  settings.py  urls.py  wsgi.py
  • On édite le fichier settings.py :
vim settings.py
  • Indication de la base de données liée à Django
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
...
  • ENGINE – Par défaut Django utilise sqlite3 : 'django.db.backends.sqlite3'.
    D’autres moteurs sont également disponibles :
    Pour utiliser PoesgreSql : 'django.db.backends.postgresql_psycopg2' ;
    Pour utiliser MySql: 'django.db.backends.mysql';
    Pour utiliser Oracle : 'django.db.backends.oracle'.
  • NAME – Le nom de votre base de données. Avec SQLite, la base de données est un fichier sur votre ordinateur.
    Dans ce cas, NAME doit être le chemin absolu complet de celui-ci, y compris le nom de fichier.
    La valeur par défaut, os.path.join(BASE_DIR, 'db.sqlite3'), stocke ce fichier dans le répertoire de votre projet.
  • Puisqu'on y est, on modifie l'encodage et le fuseau horaire :

On change :

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

Par :

LANGUAGE_CODE = 'fr-fr'

TIME_ZONE = 'Europe/Paris'

Commande de création de Modèles : manage.py migrate

On se place à la racine du projet Django

cd ~/ProjetsDjangoPy3/premierProjet/

On active le shell de pyenv pour utiliser l'une des commandes de manage.py

pyenv activate 1.8-3.4

Pour charger ou modifier les entités de la base de donnée associée au Modèles du projet Django

python manage.py migrate

Alors qu'on n'a :

python --version
Python 3.4.3

On peut tout aussi bien lancer cette commande-ci 8-)

python3 manage.py migrate

Sur la commande python manage.py migrate exécutée plutôt

  • On remarque que la commande python manage.py migrate a créé le fichier db.sqlite3
tree
.
├── db.sqlite3
├── manage.py
└── premierProjet
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-34.pyc
    │   ├── settings.cpython-34.pyc
    │   ├── urls.cpython-34.pyc
    │   └── wsgi.cpython-34.pyc
    ├── settings.py
    ├── urls.py
    └── wsgi.py

Commande manage.py startapp polls : créer les fichiers pour coder en python des Modèles

  • Toujours à la racine du projet Django pour utiliser manage.py
cd ~/ProjetsDjangoPy3/premierProjet
  • Si on est sorti du shell pyenv
pyenv activate 1.8-3.4
python manage.py startapp polls
  • On remarque que l'arborescence a changé :

Cela a crée le répertoire polls à la racine du dossier consacré au projet django :

tree
.
├── db.sqlite3
├── manage.py
├── polls
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       ├── 0001_initial.cpython-34.pyc
│   │       └── __init__.cpython-34.pyc
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-34.pyc
│   │   ├── __init__.cpython-34.pyc
│   │   └── models.cpython-34.pyc
│   ├── tests.py
│   └── views.py
└── premierProjet
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-34.pyc
    │   ├── settings.cpython-34.pyc
    │   ├── urls.cpython-34.pyc
    │   └── wsgi.cpython-34.pyc
    ├── settings.py
    ├── urls.py
    └── wsgi.py

La commande manage.py makemigrations

  • À savoir : La commande “makemigrations” permet de mettre à jour les polls (sorte de script SQL), à partir d'un modèle s'il en existe (voir plus bas).
cd ~/ProjetsDjangoPy3/premierProjet/
pyenv activate 1.8-3.4
python manage.py makemigrations
No changes detected

Le fichier models.py pour coder des Modèles

C'est là qu'on code des Modèles en python :

cd ~/ProjetsDjangoPy3/premierProjet/ && pyenv activate 1.8-3.4
vim polls/models.py
import datetime

from django.db import models
from django.utils import timezone

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text
  • Cette fois la commande “makemigrations” va créer un script de type SQL de creation et/ou mise à jour de la base de données associées au projet, par défaut ce script est le fichier “polls/migrations/0001_initial.py” :
python manage.py makemigrations polls
Migrations for 'polls':
  0001_initial.py:
    - Create model Choice
    - Create model Question
    - Add field question to choice
  • L'ORM de Django permet de générer un script de création de base de données avec tables, noms et types des champs, clés primaires et cardinalités…
    Pour voir le script créé à partir des Modèles python (classe):
python manage.py sqlmigrate polls 0001
  • Mais c'est la commande suivante qui applique les changements correspondants à ce script afin que les entités de la base de données soient l'image des classes du Modèle :
python manage.py migrate

Si ce n'est pas déjà fait :

cd ~/ProjetsDjangoPy3/premierProjet/ && pyenv activate 1.8-3.4

Pour vérifier avec le gestionnaire sqlite3 de la base de données sqlite ce qu'a créé la commande python manage.py migrate

sqlite3 db.sqlite3
sqlite> .schema

La commande "python manage.py shell" : pour interroger le Modèle et ses méthodes

Si on a désactivé le shell pyenv et/ou qu'on est sorti du dossier pour Django :

cd ~/ProjetsDjangoPy3/premierProjet/ && pyenv activate 1.8-3.4

Pour utiliser l'API Django depuis un shell python :

python manage.py shell
Et nous, même en lançant python manage.py shell

On a un shell python de version 3 ! :-D

Python 3.4.3 (default, Dec  8 2015, 11:06:14) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 
  • Évidemment, on code en python 3 dans le fichier de création de Modèle models.py !

Création d'un administrateur Django

  • On se place de le dossier de son projet Django :
cd ~/ProjetsDjangoPy3/premierProjet/
  • On crée un administrateur :
python manage.py createsuperuser
Username (leave blank to use 'hypathie'): Hypathie
Email address: hypathie@gmx.fr
Password: 
Password (again): 
Superuser created successfully.
  • Et maintenant on peut accéder à la gestion de son projet depuis son navigateur :
python manage.py runserver 192.168.0.26:8000
Modifier 192.168.0.26 par l'ip de la machine sur laquelle le projet est installé.

Pour le savoir :

ifconfig
  • remarques :
  1. L'avantage de l'ip de la machine c'est de pouvoir se connecter à son application depuis son navigateur depuis une machine distante installer sous le même routeur (dans cet exemple).
  • On tape dans son navigateur par exemple :
192.168.0.26:8000/admin

Notes

Installer un gabarit : base_site.html

Voir : https://docs.djangoproject.com/fr/1.8/intro/tutorial02/#customizing-your-project-s-templates

find /home/hypathie/ -print0 |grep -FzZ "admin/base_site.html"
cd /home/hypathie/.pyenv/versions/3.4.3/envs/1.8-3.4/lib/python3.4/site-packages/django/contrib/admin/templates/admin
cp base_site.html /home/hypathie/ProjetsDjangoPy3/premierProjet/templates/admin/

Personnaliser l'index de la page d'administration

Voir : https://docs.djangoproject.com/fr/1.8/intro/tutorial02/#customize-the-admin-index-page

cp /home/hypathie/.pyenv/versions/3.4.3/envs/1.8-3.4/lib/python3.4/site-packages/django/contrib/admin/templates/admin/index.html /home/hypathie/ProjetsDjangoPy3/premierProjet/templates/admin/
utilisateurs/hypathie/tutos/developpement-pyhon-utiliser-django.txt · Dernière modification: 06/01/2016 10:18 par Hypathie

Pied de page des forums

Propulsé par FluxBB