Outils pour utilisateurs

Outils du site


blog

Python Flask Gunicorn - Alternative à CGI

Voir :

Alternative à Flask :

  • CherryPy
  • Falcon

Alternative à Unicorn

  • Uvicorn
apt-get install python3-flask gunicorn3

wsgi.py

#! /usr/bin/env python3
 
from plopweb import app                 
 
if __name__ == "__main__":             
    app.run(                                                                                          
            host="0.0.0.0",
            port=int("5001")
            )

plopweb.py

#! /usr/bin/env python3    
 
import subprocess                                                  
from flask import Flask, request, send_from_directory, after_this_request, abort
app = Flask(__name__)
from subprocess import call
 
LOGFILE='/tmp/plop.txt'
CMD_ANSIBLE='/usr/bin/ansible-playbook'
 
def bash_command(cmd):
    subprocess.Popen(cmd, shell=True, executable='/bin/bash')
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
@app.route('/hello', methods=['POST'])
def hello():
    playbook = request.form['playbook']
    ip = request.environ['REMOTE_ADDR']
    bash_command('echo ' + CMD_ANSIBLE + ' ' + playbook +' -i ' + ip + ',' + '>>' + LOGFILE + ' 2>&1')
    return `
 
if __name__ == '__main__':
    app.run(
            debug=True,
            host="0.0.0.0",
            port=int("5001")
            )

wsgi.py

#! /usr/bin/env python3
 
from plopweb import app
 
if __name__ == "__main__":
    app.run(
            host="0.0.0.0",
            port=int("5001")
            )
gunicorn3 --bind 0.0.0.0:5001  wsgi:app

Avec ça vous pouvez faire un script SystemD ou utiliser Supervisor, et mettre un nginx en reverse proxy

Exemple supervisor

apt-get install supervisor

supervisor-plopweb.conf

[program:plopweb]
command = gunicorn3 --bind 127.0.0.1:8000  wsgi:app
directory = /home/pkiweb/bin
user = plopweb

Exemple de conf nginx

plopweb

server {
        listen 443 ssl;
        server_name plopweb.lan ;
 
        access_log /var/log/nginx/plopweb-ssl-access.log;
        error_log  /var/log/nginx/plopweb-ssl-error.log;
 
        ssl_certificate     /etc/nginx/ssl/plopweb.lan.combined.crt;
        ssl_certificate_key /etc/nginx/ssl/plopweb.lan.key;
        ssl_client_certificate /etc/nginx/ssl/ca.crt;
        ssl_verify_client on;
 
        location / {
                proxy_pass http://localhost:8000;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
        }
}
2025/03/24 15:06

Python, Flask et Supervisor à la place des vieilles CGI

Quand nous faisons une requête web (un POST par exemple) sur une URL, nous souhaitons lancer la commande ci-dessous

./script.sh -a -f prefix-/${POST_VAR} >> plop.log 2>&1

Voici une alternative aux CGI

Si besoin activer les dépôts backports :

echo "deb http://ftp.debian.org/debian jessie-backports main" >> /etc/apt/sources.list
 
apt-get update
apt-get install python3-flask gunicorn3 supervisor

plop.py

#! /usr/bin/env python3
 
import subprocess
import re
 
from flask import Flask, request, send_from_directory, after_this_request, abort
app = Flask(__name__)
 
from subprocess import call
 
LOGFILE='plop.log'
 
# MUST BE ENDED BY "/"
DL_DIR='/home/plop/foo/'
 
SCRIPT_ARGS='-a -f'
 
SCRIPT='./script.sh'
 
def bash_command(cmd):
    subprocess.Popen(cmd, shell=True, executable='/bin/bash')
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
@app.route('/hello/', methods=['POST'])
def hello():
    var_post = request.form['var_post']
    bash_command(SCRIPT + ' ' + SCRIPT_ARGS + ' ' + 'prefix-' + var_post + ' >>' + LOGFILE + ' 2>&1')
    return `
 
@app.route('/dl/<codename>')
def download_file(filename):
    @after_this_request
    def delete_file(response):
        if re.match('^prefix-.*\.key$', filename):
            bash_command('shred -u ' + DL_DIR + filename)
        return response
    if re.match('^prefix-', filename):
        return send_from_directory(DL_DIR, filename, as_attachment=True)
    else:
        abort(403)
 
if __name__ == '__main__':
    app.run(
            #debug=True,
            #host="0.0.0.0",
            port=int("5001")
            )

Pour tester sur le post TCP 5001 avant du passer en prod sur le port 8000

wsgi.py

#! /usr/bin/env python3
 
from plop import app
 
if __name__ == "__main__":
    app.run()

/etc/supervisor/conf.d/plop.conf

[program:plop]
command = gunicorn3 --bind 127.0.0.1:8000  wsgi:app
directory = /home/plop/bin
user = plop

Note : A la place du Supervisor elle est possible d'utiliser SystemD ou S6

2025/03/24 15:06

Python cours formation

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Voir :

  • PEP 8
  • pep257

Formations :

Apprendre en ligne

Bases :

Avancé :

  • Solutions d'optimisation
  • Interfaçage avec C / C++ Swig
  • Typage statique avec mypy et le module typing
  • Les annotations de types (avec mypy, pypright, pyre ou pytypes)
  • Programmation par contract avec PyContracts

Linter / Formater :

Gérer les exceptions et les erreurs :

  • try except finally
  • raise
  • Exception
  • assert
  • traceback
  • pdb

Les Libs:

P.O.O.

  • Attributs et méthodes de classe/instance
  • Les méthodes spéciales (surcharges d'opérateurs, casting, constructeur, destructeur, …)
  • Héritage, surcharge, polymorphisme, la classe object
  • L’héritage simple, l’héritage multiple et le polymorphisme
  • L'héritage multiple et le MRO (Method Resolution Order)
  • Bonnes pratiques de la programmation objet avec Python
  • Les méta-classes et l'héritage multiple

La stdlib - Parcours de quelques modules phares :

Docker / Containers :

Aller plus loin Présentation des objets et fonctions avancés

Les fonctions

def create_hello_world_message(name : str) -> str:
    """
    Creates a personalized greeting message for the given name.
 
    Parameters:
        - name (str) : The name for which the message is created.
 
    Returns:
        - hello_world_message (str) : A personalized greeting message for the given name.
 
    Raises:
        - ValueError : If the given name is empty or None.
    """
 
    if not name:
 
        raise ValueError
 
    hello_world_message = f'Hello World, {name}!'
 
    print(f'name                : { name }')
    print(f'hello_world_message : { hello_world_message }')
 
    return hello_world_message

Import

import os
import sys
sys.path.append(os.path.dirname(os.getcwd()))
 
import plop

Sciences - math

from sympy import symbols, Eq, solve
 
B, G = symbols('B G')
eq1 = Eq(B, 0.3 * B + 5 * G)
eq2 = Eq(100 * B + 200 * G, 1000)
solution = solve(eq1, eq2), (B, G))
solution[B]

Mutable / immutable

Voir aussi : deepcopy

lst=[1,2,3];
print(list(map(lambda x: [x],lst)));

Autres

import random
random.randint(1,9)
export PYTHONUNBUFFERED=1

Linter

Flake8
ansible-csv-inventory.py:30:80: E501 line too long (82 > 79 characters)

Pour ignorer l'erreur

tox.ini

[flake8]
extend-ignore = E501

Autres

$ ansible-test sanity --list-tests
action-plugin-docs
ansible-doc
changelog
compile
empty-init
ignores
import
line-endings
no-assert
no-get-exception
no-illegal-filenames
no-smart-quotes
pep8
pslint
pylint
replace-urlopen
runtime-metadata
shebang
shellcheck
symlinks
use-argspec-type-path
use-compat-six
validate-modules
yamllint
2025/03/24 15:06

Python - Debug

pdb

Voir https://docs.python.org/fr/3/library/pdb.html

Insérer

import pdb; pdb.set_trace()

Ou lancer le programme en mode debug sans modifier le code

python2 -m pdb /usr/local/bin/plop.py
Syntax

b pour Breakpoint \ Ajout un point d'arrêt ou liste les points d'arrêt

l ou ll \ Affiche une portion du code

cl(ear) \ Clear breakpoint

p ou pp \ Affiche la valeur d'une variable

! statement \ Executer du code Python. Dans bien des cas le ! pourra être omis

s(tep) \ Exécute la ligne en cours, s'arrête à la première occasion possible (soit dans une fonction qui est appelée, soit sur la ligne suivante de la fonction courante).

n(ext) \ La différence entre next et step est que step s'arrête dans une fonction appelée, tandis que next exécute les fonctions appelées à (presque) pleine vitesse

restart \ Redémarrer le programe Python débugé.

quit \

Exemple
(Pdb) b plop:49
Breakpoint 1 at /usr/local/bin/plop.py:49
(Pdb) r
> /usr/local/bin/plop.py(49)__init__()
-> self.root_wrappers = root_wrappers
(Pdb) p self.svcid
'event-abcd'
(Pdb) self.svcid='event-abcdef'
(Pdb) p self.svcid
'event-abcdef'
(Pdb) r
--Return--
> /usr/local/bin/plop.py(50)__init__()->None
-> self.pwd = pwd.getpwnam(self.svcid)
(Pdb) p self.svcid
'event-abcdef'
(Pdb) r
KeyError: 'getpwnam(): name not found: event-abcdef'
> /usr/local/bin/plop.py(283)fetch_svcids()
-> return [CronTab(site, svcid['nom'], svcid['active'], options, env, root, template_wrapper, root_wrappers) for svcid in svcids]
(Pdb) p [CronTab(site, svcid['nom'], svcid['active'], options, env, root, template_wrapper, root_wrappers) for svcid in svcids]
*** KeyError: KeyError('getpwnam(): name not found: event-abcdef',)
(Pdb) self.svcid='event-abcd'
*** NameError: name 'self' is not defined
(Pdb) b
Num Type         Disp Enb   Where
1   breakpoint   keep yes   at /usr/local/bin/plop.py:49
        breakpoint already hit 1 time
(Pdb) restart
Restarting /usr/local/bin/plop.py with arguments:

> /usr/local/bin/plop.py(6)<module>()
-> """

Ipdb

pip install ipdb
import ipdb; ipdb.set_trace()

trace

python -m trace --trace somefile.py
2025/03/24 15:06
blog.txt · Dernière modification : de 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki