cristian Lozano

Recollir informació POST en Python des d'un servidor web

Per a recollir informació POST al nostre servidor python haurem de seguir aquests passos:

pip install flask
pip install flask flask-cors

Instal·lació de llibreries, de primeres ens donarà error, per com tenim preparada la nostra màquina Vagrant.

error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.
    
    If you wish to install a non-Debian-packaged Python package,
    create a virtual environment using python3 -m venv path/to/venv.
    Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
    sure you have python3-full installed.
    
    If you wish to install a non-Debian packaged Python application,
    it may be easiest to use pipx install xyz, which will manage a
    virtual environment for you. Make sure you have pipx installed.
    
    See /usr/share/doc/python3.11/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.

Aquest error externally-managed-environment vol dir que Debian (o una derivada com Ubuntu 22.04 en endavant) està protegint el sistema perquè no facis pip install globalment fora del seu sistema de paquets (apt), per evitar trencar dependències del sistema.

sudo apt install python3-venv -y

Per aconseguir instal·lar les llibreries virtualitzarem un entorn virtual amb les següents comandes. Primer instal·lem python3-venv

python3 -m venv venv

Creació entorn virtual a la carpeta actual.

source venv/bin/activate 

Activació de l’entorn.

pip install flask  
pip install flask flask-cors

Tornem a instal·lar les llibreries.

vim servidorpost.py

Fem la creació del nostre servidor amb python amb vim.

#Importació de llibreries
from flask import Flask, request, jsonify
from flask_cors import CORS

#Creació aplicació FLask
app = Flask(__name__)
CORS(app) #Permet peticios de js extern

#Definim la ruta per escoltar i només accepta métode POST
@app.route('/dades', methods=['POST'])
def rebre_dades():
    #Llegim el json
    dades = request.get_json()
    #Mostrem les dades
    print("JSON rebut:", dades)
    #Retornem una resposta json de recepció
    return jsonify({'estat': 'rebut', 'dades': dades}), 200

#Instrucció executar directament aquest fitxer
if __name__ == '__main__':
    #Iniciem servidor Flask de manera local al nostre equip
    app.run(host='localhost', port=5000)
python3 servidorpost.py

Executem el python per escoltar.