Per poter interagire tra una pagina HTML e un programma python si deve utilizzare il modulo flask.
installazione del modulo flask:
1 |
sudo pip install Flask |
se non dovesse funzionare il programma per un errore: header CORS “Access-Control-Allow-Origin” mancante. Codice di stato: 200. potrebbe essere necessario installare il modulo CORS
1 |
<sup>sudo pip install sudo pip install flask-cors</sup> |
Per fare un esempio creare un file html o php in questa maniera:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> <form id="form"> <input type="text" id="a" name="a" value="1"> <input type="text" id="b" name="b" value="2"> <button type="submit" id="submit">Submit</button> </form> <div id="result"></div> <script> const form = document.getElementById('form'); const result = document.getElementById('result'); form.addEventListener('submit', async (event) => { event.preventDefault(); const response = await fetch('http://localhost:5000/sum', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ a: form.elements.a.value, b: form.elements.b.value }) }); const data = await response.json(); result.innerHTML = `Result: ${data.result}`; }); </script> </body> </html> |
creare un file python con estensione .py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# app.py from flask import Flask, jsonify, request from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/sum', methods=['POST']) def calcola(): print("prova di calcolo") data = request.get_json() a = data['a'] b = data['b'] c = int(a) + int(b) return jsonify({'result': c}) if __name__ == '__main__': app.run(host='127.0.0.1') |
avviare il codice per farlo rimanere in ascolto sulla porta 5000 con il comando:
1 |
python app.py |
La porta 5000 deve essere aperta nel server
nel browser visitare la pagina html creata precedentemente