Post

_python-flask

_python-flask

_python-flask

Flask

RESTful API Python+Flask

Répertoire documentation

Version python

Version python installée python –version Python 2.7.9

virtualenv

Installation pip sudo apt-get install python-pip Installation virtualenv sudo pip install virtualenv

Une fois que vous avez installé virtualenv, exécuter les commandes suivantes sans le préfixe sudo.

1
2
3
mkdir ~/restful
cd restful
virtualenv vflask

<file> New python executable in vflask/bin/python Installing setuptools, pip…done. </file> Maintenant, chaque fois que vous souhaitez travailler sur un projet, il suffit d’activer l’environnement correspondant. Sur OS X et Linux, procédez comme suit:

1
2
. vflask/bin/activate
(vflask)xino@olinuxino:~/restful$

Vous devriez maintenant être en mesure d’utiliser votre virtualenv (remarquez comment l’invite de votre shell a changé pour montrer l’environnement actif).

flask/installation

Installer flask (vflask)xino@olinuxino:~/restful$ pip install flask

Une simple page web nano app_rest.py

1
2
3
4
5
6
7
8
9
10
11
12
:::python
#!vflask/bin/python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "Hello, World!"

if __name__ == '__main__':
    app.run(debug=True)

Exécution code serveur chmod a+x app_rest.py ./app_rest.py <file>

  • Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
  • Restarting with stat </file>

Sur une autre fenêtre terminal curl http://localhost:5000 Hello, World!

RESTful services Python Flask

HTTP Method URI Action

GET http://[hostname]/todo/api/v1.0/tasks Retrieve list of tasks curl -u “yann:spm” -i https://mps.ovh/todo/api/v1.0/tasks GET http://[hostname]/todo/api/v1.0/tasks/[task_id] Retrieve a task curl -u “yann:spm” -i https://mps.ovh/todo/api/v1.0/tasks/2 POST http://[hostname]/todo/api/v1.0/tasks Create a new task curl -u “yann:spm” -i -H “Content-Type: application/json” -X POST -d ‘{“title”:”Read a book”}’ https://mps.ovh/todo/api/v1.0/tasks PUT http://[hostname]/todo/api/v1.0/tasks/[task_id] Update an existing task curl -u “yann:spm” -i -H “Content-Type: application/json” -X PUT -d ‘{“description”:”essai”,”done”:true}’ https://mps.ovh/todo/api/v1.0/tasks/3 DELETE http://[hostname]/todo/api/v1.0/tasks/[task_id] Delete a task

We can define a task as having the following fields:

1
2
3
4
*id: unique identifier for tasks. Numeric type.
*title: short task description. String type.
*description: long task description. Text type.
*done: task completion state. Boolean type.

uWSGI

1
2
3
4
5
(vflask)xino@olinuxino:~/restful$ sudo apt-get install build-essential python python-dev
(vflask)xino@olinuxino:~/restful$ pip install uwsgi   #patienter ,installation très longue !!! `<file>` Collecting uwsgi
Using cached uwsgi-2.0.11.2.tar.gz Building wheels for collected packages: uwsgi
Running setup.py bdist_wheel for uwsgi
Stored in directory: /home/xino/.cache/pip/wheels/a7/33/50/7bb71db37249e30aabe7c1247f283bc19e299b533597c8bafd Successfully built uwsgi Installing collected packages: uwsgi Successfully installed uwsgi-2.0.11.2 `</file>`

Configurer nginx

Sous (vflask)xino@olinuxino:~/restful$

Supprimer le site par défaut sudo rm /etc/nginx/sites-enabled/default Configuration serveur restful nano restful_nginx.conf

1
2
3
4
5
6
7
8
9
10
11
12
server {
    listen      80;
    server_name localhost;
    charset     utf-8;
    client_max_body_size 75M;

    location / { try_files $uri @yourapplication; }
    location @yourapplication {
        include uwsgi_params;
        uwsgi_pass unix:/home/xino/restful/restful_uwsgi.sock;
    }
}

Lien de la configuration et relance serveur sudo ln -s /home/xino/restful/restful_nginx.conf /etc/nginx/conf.d/ sudo /etc/init.d/nginx restart

Configurer uWSGI

Créer un fichier de configuration /home/xino/restful/restful_uwsgi.ini: nano /home/xino/restful/restful_uwsgi.ini <file> [uwsgi] #application’s base folder

base = /home/xino/restful

#python module to import

app = app_rest module = %(app)

home = %(base)/vflask pythonpath = %(base)

#socket file’s location

socket = /home/xino/restful/%n.sock

#permissions for the socket file

chmod-socket = 666

#the variable that holds a flask application inside the module imported at line #6

callable = app

#location of log files

logto = /var/log/uwsgi/%n.log </file> Création dossier pour les fichiers log uwsgi, et changer le propriétaire : sudo mkdir -p /var/log/uwsgi sudo chown -R xino:xino /var/log/uwsgi Exécuter uWSGI avec le nouveau fichier de configuration et tester par curl: uwsgi –ini /home/xino/restful/restful_uwsgi.ini Ctrl C pour terminer

uWSGI Emperor

Maintenant il faut exécuter uWSGI en arrière-plan comme service , c’est le rôle de uWSGI Emperor exec /home/xino/restful/vflask/bin/uwsgi –master –emperor /etc/uwsgi/vassals –die-on-term –uid www-data –gid www-data –logto /var/log/uwsgi/emperor.log Les fichiers de configuration sont dans /etc/uwsgi/vassals. Créons ce dossier et faire des liens symboliques sur le fichier de configuration que nous avons créé: sudo mkdir -p /etc/uwsgi/vassals sudo ln -s /home/xino/restful/restful_uwsgi.ini /etc/uwsgi/vassals En outre, la dernière ligne indique le l’utilisateur qui sera utilisé pour exécuter le démon est www-data. sudo chown -R www-data:www-data /home/xino/restful/ sudo chown -R www-data:www-data /var/log/uwsgi/ Depuis deux, nginx et uwsgi, sont maintenant géré par le même utilisateur, nous pouvons apporter une amélioration de la sécurité à notre configuration de uwsgi. Ouvrez le fichier de config uwsgi et modifier la valeur de la commande chmod-socket 666 à 644: sudo nano /home/xino/restful/restful_uwsgi.ini <file> […] #permissions for the socket file

chmod-socket = 644 […] </file> Démarrage de l’exécutable au lancement de debian sudo nano /etc/rc.local

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
:::bash
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
exec /home/xino/restful/vflask/bin/uwsgi --master --emperor /etc/uwsgi/vassals --die-on-term --uid www-data --gid www-data --logto /var/log/uwsgi/emperor.log
exit 0

RESTful Client

Version python

Version python installée python –version Python 2.7.3

virtualenv

Installation pip sudo apt-get install python-pip Installation virtualenv sudo pip install virtualenv

Essai 1

Une fois que vous avez installé virtualenv, exécuter les commandes suivantes sans le préfixe sudo.

1
2
3
mkdir ~/mon_projet
cd mon_projet
virtualenv venv

<file> New python executable in venv/bin/python Installing setuptools, pip…done. </file> Maintenant, chaque fois que vous souhaitez travailler sur un projet, il suffit d’activer l’environnement correspondant. Sur OS X et Linux, procédez comme suit:

1
2
. venv/bin/activate
(venv)yann@vps47338:/home/yann/mon_projet$

Vous devriez maintenant être en mesure d’utiliser votre virtualenv (remarquez comment l’invite de votre shell a changé pour montrer l’environnement actif).

Essai 2

Python possède une quantité incroyable d’extensions/bibliothèques que vous pouvez installer et utiliser dans vos projets. Mais quand on travaille sur plusieurs projets à la fois (et pas forcément que sur du web), on peut arriver à des problèmes de dépendances. Mon projet A nécessite truc en version 1, mon projet B truc en version 2…

Une bonne pratique consiste à créer un environnement virtuel pour nos packages, avec un outil comme virtualenv, de cette manière cet environnement sera complétement indépendant du reste du système.

1
2
3
4
5
#easy_install virtualenv fait avec pip
cd ~
virtualenv mon_projet   #va créer le dossier mon_projet
cd mon_projet
source bin/activate # pour l'activer

Le répertoire mon_projet sera crée avec tout le nécessaire. Si votre prompt change légèrement <file>(mon_projet)yann@vps47338:/home/yann/mon_projet$</file> c’est que la manipulation a fonctionné. Virtualenv est très puissant, vous pouvez même lui passer la version de Python en paramètre.

1
2
virtualenv -p /usr/local/bin/python3.3 mon_projet
virtualenv -p /usr/local/bin/pypy mon_projet

Pour désactiver un virtualenv il suffit de lancer la commande deactivate dans le terminal.

Flask micro-framework

Flask est un micro-framework Python. Contrairement à Django qui fait beaucoup de choses tout seul (ORM, validations formulaires, back-end admin…), Flask reste simple et c’est à vous de lui coder/rajouter ces composants à la main (BYOB).

Parmis les avantages de Flask, on retrouve :

1
2
3
4
5
*Base code minimale, environ 800 lignes.
*Très bien testé, environ 1 500 lignes.
*Très bonne documentation (plus de 200 pages).
*Possède un système de template (Jinja2).
*Pousse à coder son application sous forme de services, ce qui est une bonne chose.

Installons Flask avec pip dans l’environnement : pip install Flask

Appli minima (Essai 1)

Dans l’environnement du projet <wrap hi>(venv)yann@vps47338:/home/yann/mon_projet$</wrap> nano hello.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
:::python
# coding=UTF-8
# importation du module Flask
from flask import Flask
# instancier une occurence de Flask dans la variable app
app = Flask(__name__)
#
# ce décorateur permet d'indiquer à Flask que, pour obtenir le contenu envoyé lorsque l'URL "/" est demandée
@app.route('/')
# la fonction décorée ci dessous est à utiliser
def hello():
# on définit une fonction appelée "hello" (peu importe le nom) , liée à l'URL "/"
    return 'Salut le monde!'
# cette fonction retourne simplement "Salut le monde!" et c'est le retour de cette fonction qui sera renvoyé par Flask au client web
#
# Cette ligne permet de n'exécuter le contenu du "if" que si le script est directement exécuté
# S'il était importé à partir d'un autre fichier, cette condition serait fausse
if __name__ == '__main__':
    app.run()

Lancement du serveur

1
2
3
python hello.py

 * Running on http://127.0.0.1:5000/

Un appel renvoie “Salut le monde!”

1
2
curl http://127.0.0.1:5000/
Salut le monde!

Trace de l’appel sur le serveur

1
127.0.0.1 - - [25/Jul/2014 18:20:06] "GET / HTTP/1.1" 200 -

Serveur visible de l’extérieur

Si vous exécutez le serveur, vous remarquerez que le serveur est accessible uniquement à partir de votre propre ordinateur. C’est la valeur par défaut, car en mode de débogage un utilisateur de l’application peut exécuter du code Python arbitraire sur votre ordinateur.

Si vous avez désactivé le “debugg” ou avez confiance aux utilisateurs de votre réseau, vous pouvez rendre le serveur accessible au public en changeant simplement l’appel du “run” (méthode) pour ressembler à ceci: app.run(host=’0.0.0.0’) Cela indique à votre système d’exploitation pour écouter sur toutes les adresses IP publiques.

Appli minima (Essai 2)

Une fois installé, on va écrire notre premier script. Pour cela on va créer un dossier mon_projet/app et à la racine de ce dossier un fichier mon_projet/app/app.py, comme par exemple :

1
2
3
4
5
6
7
8
9
10
11
12
13
:::python
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Salut le monde!"

if __name__ == "__main__":
    app.run()

Pour tester ce code, il suffit juste de lancer la commande suivante. Et d’ouvrir le navigateur sur l’URL qui sera affichée dans la console.

1
2
3
$ python app.py

 * Running on http://127.0.0.1:5000/

Flask/Microblog

Basé sur The Flask Mega-Tutorial de Miguel Gringberg

Requirements

If you have a computer that runs Python 2.6 or 2.7 then you are probably good to go. The tutorial application should run just fine on Windows, OS X and Linux. (If you intend to follow this tutorial on Python 3 you will need to make some small changes, I wrote this tutorial before Flask had support for Python 3).

The tutorial assumes that you are familiar with the terminal window (command prompt for Windows users) and know the basic command line file management functions of your operating system. If you don’t, then I recommend that you learn how to create directories, copy files, etc. using the command line before continuing.

Finally, you should be somewhat comfortable writing Python code. Familiarity with Python modules and packages is also recommended.

Installing Flask

Okay, let’s get started!

If you haven’t yet, go ahead and install Python 2.7.

Now we have to install Flask and several extensions that we will be using. My preferred way to do this is to create a virtual environment where everything gets installed, so that your main Python installation is not affected. As an added benefit, you won’t need root access to do the installation in this way.

So, open up a terminal window, choose a location where you want your application to live and create a new folder there to contain it. Let’s call the application folder microblog.

1
2
3
cd ~
mkdir microblog
cd microblog

Next, download virtualenv.py and put it inside the new folder.

To create the virtual environment enter the following command:

1
2
wget https://raw.github.com/pypa/virtualenv/1.9.X/virtualenv.py
python virtualenv.py flask

The above command creates a complete Python environment inside the flask folder.

Virtual environments can be activated and deactivated, if desired. An activated environment adds the location of its bin folder to the system path, so that for example, when you type python you get the environment’s version and not the system’s one. I personally do not like this feature, so I never activate any of my environments and instead just invoke the interpreter I want by typing its pathname.

If you are on Linux, OS X or Cygwin, install flask and extensions by entering the following commands, one after another:

1
2
3
4
5
6
7
8
9
10
11
12
flask/bin/pip install flask==0.9
flask/bin/pip install flask-login
flask/bin/pip install flask-openid
flask/bin/pip install flask-mail==0.7.6
flask/bin/pip install sqlalchemy==0.7.9
flask/bin/pip install flask-sqlalchemy==0.16
flask/bin/pip install sqlalchemy-migrate==0.7.2
flask/bin/pip install flask-whooshalchemy==0.55a
flask/bin/pip install flask-wtf==0.8.4
flask/bin/pip install pytz==2013b
flask/bin/pip install flask-babel==0.8
flask/bin/pip install flup

These commands will download and install all the packages that we will use for our application.

Note that we are going to use Flask 0.9, which is not the latest version. Flask 0.10 hasn’t been out for long and some extensions haven’t been updated to work well with it. Also there are some incompatibilities between packages and the latest version of pip that are sorted out by giving specific versions to install.

If the installation of all the packages was successful you can delete virtualenv.py, since we won’t need it anymore.

“Hello, World” in Flask

You now have a flask sub-folder inside your microblog folder that is populated with a Python interpreter and the Flask framework and extensions that we will use for this application. Now it’s time to write our first web application!

After you cd to the microblog folder, let’s create the basic folder structure for our app:

1
2
3
4
mkdir app
mkdir app/static
mkdir app/templates
mkdir tmp

The app folder will be where we will put our application package. The static sub-folder is where we will store static files like images, javascripts, and style sheets. The templates sub-folder is obviously where our templates will go.

Let’s start by creating a simple init script for our app package (file app/__init__.py):

1
2
3
4
from flask import Flask

app = Flask(__name__)
from app import views

The script above simply creates the application object (of class Flask) and then imports the views module, which we haven’t written yet.

The views are the handlers that respond to requests from web browsers. In Flask views are written as Python functions. Each view function is mapped to one or more request URLs.

Let’s write our first view function (file app/views.py):

1
2
3
4
5
6
from app import app

@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!"

This view is actually pretty simple, it just returns a string, to be displayed on the client’s web browser. The two route decorators above the function create the mappings from urls / and /index to this function.

The final step to have a fully working web app is to create a script that starts up the development web server with our application. Let’s call this script run.py, and put it in the root folder:

1
2
3
#!flask/bin/python
from app import app
app.run(debug = True)

The script simply imports the app variable from our app package and invokes its run method to start the server. Remember that the app variable holds the Flask instance, we created it above.

To start the app you just run this script. On OS X, Linux and Cygwin you have to indicate that this is an executable file before you can run it:

1
chmod a+x run.py

Then the script can simply be executed as follows:

1
./run.py

After the server initializes it will listen on port 5000 waiting for connections. Now open up your web browser and enter the following URL in the address field: http://localhost:5000

Alternatively you can use the following URL:http://localhost:5000/index

Do you see the route mappings in action? The first URL maps to /, while the second maps to /index. Both routes are associated to our view function, so they produce the same result. If you enter any other route you will get an error, since only these two have been mapped to a view function.

When you are done playing with the server you can just hit Ctrl-C to stop it.

And with this I conclude this first installment of this tutorial.

Cet article est sous licence CC BY 4.0 par l'auteur.