Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8015

Python • Re: problem with flask app.py

$
0
0
First of all thanks for helping me. For the question you asked:
1) Pi is still running without any problem i can get inside
2) I gave to pi a static IP which its work correctly
3)Server Apache is still running:

Code:

(venv) maurizio@raspberrypi:/var/www/html/magazzino $ systemctl status apache2● apache2.service - The Apache HTTP Server     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; preset: enabled)     Active: active (running) since Tue 2025-03-18 20:36:56 CET; 12h ago       Docs: https://httpd.apache.org/docs/2.4/    Process: 588 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)    Process: 2904 ExecReload=/usr/sbin/apachectl graceful (code=exited, status=0/SUCCESS)   Main PID: 693 (apache2)      Tasks: 6 (limit: 760)        CPU: 3.803s     CGroup: /system.slice/apache2.service             ├─ 693 /usr/sbin/apache2 -k start             ├─2917 /usr/sbin/apache2 -k start             ├─2918 /usr/sbin/apache2 -k start             ├─2919 /usr/sbin/apache2 -k start             ├─2920 /usr/sbin/apache2 -k start             └─2921 /usr/sbin/apache2 -k startmar 18 20:36:54 raspberrypi systemd[1]: Starting apache2.service - The Apache HTTP Server...mar 18 20:36:56 raspberrypi apachectl[616]: AH00558: apache2: Could not reliably determine the server's fully qualified domain nam>mar 18 20:36:56 raspberrypi systemd[1]: Started apache2.service - The Apache HTTP Server.mar 19 00:00:11 raspberrypi systemd[1]: Reloading apache2.service - The Apache HTTP Server...mar 19 00:00:12 raspberrypi apachectl[2907]: AH00558: apache2: Could not reliably determine the server's fully qualified domain na>mar 19 00:00:12 raspberrypi systemd[1]: Reloaded apache2.service - The Apache HTTP Server.

maybe it says something i posted because for me i didn't see any error but as i said i'm not an IT :(
4)The terminal where the app.py run is after few hours it send me this output:

Code:

^C(venv) maurizio@raspberrypi:/var/www/html/magazzino $ python3 app.py * Serving Flask app 'app' * Debug mode: offclient_loop: send disconnect: Broken pipe
Is maybe this one the problem? This was this morning but the window terminal was still on
5) if i ping the Raspberry i do not have any reason to see issues:

Code:

maurizio@maurizio-MS-7B86:~$ ping 192.168.1.160PING 192.168.1.160 (192.168.1.160) 56(84) bytes of data.64 bytes from 192.168.1.160: icmp_seq=1 ttl=64 time=53.7 ms64 bytes from 192.168.1.160: icmp_seq=2 ttl=64 time=6.15 ms64 bytes from 192.168.1.160: icmp_seq=3 ttl=64 time=5.97 ms^C--- 192.168.1.160 ping statistics ---3 packets transmitted, 3 received, 0% packet loss, time 2002msrtt min/avg/max/mdev = 5.970/21.936/53.685/22.450 ms
This is the app.py code

Code:

from flask import Flask, render_template, jsonify, requestimport requestsimport loggingimport mysql.connectorapp = Flask(__name__)# Configurazione del loggerlogging.basicConfig(filename='/home/maurizio/magazzino.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# Configurazione del databasedb_config = {    'host': 'xxx',    'user': 'xxx',    'password': 'xxx',    'database': 'xxx'}@app.route('/')def magazzino():    return render_template('magazzino.html')@app.route('/api/prodotti')def get_prodotti():    logger.info("Richiesta GET /api/prodotti")    try:        conn = mysql.connector.connect(**db_config)        cursor = conn.cursor(dictionary=True)        cursor.execute("SELECT id, nome, quantita FROM prodotti")        prodotti = cursor.fetchall()        cursor.close()        conn.close()        logger.info(f"Risposta API: {prodotti}")        return jsonify(prodotti)    except mysql.connector.Error as e:        logger.error(f"Errore nella richiesta: {e}")        return jsonify({'error': str(e)}), 500@app.route('/api/quantita/<int:id_prodotto>')def get_quantita(id_prodotto):    logger.info(f"Richiesta GET /api/quantita/{id_prodotto}")    try:        conn = mysql.connector.connect(**db_config)        cursor = conn.cursor(dictionary=True)        cursor.execute("SELECT quantita FROM prodotti WHERE id = %s", (id_prodotto,))        result = cursor.fetchone()        cursor.close()        conn.close()        if result:            logger.info(f"Risposta API PHP: {result}")            return jsonify(result)        else:            return jsonify({'error': 'Prodotto non trovato'}), 404    except mysql.connector.Error as e:        logger.error(f"Errore nella richiesta: {e}")        return jsonify({'error': str(e)}), 500@app.route('/api/update/<int:id_prodotto>', methods=['POST'])def update_quantita(id_prodotto):    logger.info(f"Richiesta POST /api/update/{id_prodotto}")    try:        data = request.get_json()        quantita = data['quantita']        conn = mysql.connector.connect(**db_config)        cursor = conn.cursor()        cursor.execute("UPDATE prodotti SET quantita = %s WHERE id = %s", (quantita, id_prodotto))        cursor.execute("INSERT INTO movimentazioni (id_prodotto, data_ora, quantita, tipo_movimento) VALUES (%s, NOW(), %s, 'aggiunta')", (id_prodotto, quantita))        conn.commit()        cursor.close()        conn.close()        logger.info(f"Quantità aggiornata per il prodotto {id_prodotto}")        return jsonify({'success': 'Quantità aggiornata correttamente'})    except Exception as e:        logger.error(f"Errore durante l'aggiornamento: {e}")        return jsonify({'error': str(e)}), 500@app.route('/api/sottrai/<int:id_prodotto>', methods=['POST'])def sottrai_quantita(id_prodotto):    logger.info(f"Richiesta POST /api/sottrai/{id_prodotto}")    try:        data = request.get_json()        quantita_da_sottrarre = data['quantita']        conn = mysql.connector.connect(**db_config)        cursor = conn.cursor()        cursor.execute("UPDATE prodotti SET quantita = quantita - %s WHERE id = %s", (quantita_da_sottrarre, id_prodotto))        cursor.execute("INSERT INTO movimentazioni (id_prodotto, data_ora, quantita, tipo_movimento) VALUES (%s, NOW(), %s, 'sottrazione')", (id_prodotto, quantita_da_sottrarre))        conn.commit()        cursor.close()        conn.close()        logger.info(f"Quantità sottratta per il prodotto {id_prodotto}")        return jsonify({'success': 'Quantità sottratta correttamente'})    except Exception as e:        logger.error(f"Errore durante la sottrazione: {e}")        return jsonify({'error': str(e)}), 500@app.route('/api/movimentazioni/<int:id_prodotto>')def get_movimentazioni(id_prodotto):    logger.info(f"Richiesta GET /api/movimentazioni/{id_prodotto}")    try:        conn = mysql.connector.connect(**db_config)        cursor = conn.cursor(dictionary=True)        cursor.execute("SELECT data_ora, quantita, tipo_movimento FROM movimentazioni WHERE id_prodotto = %s ORDER BY data_ora DESC", (id_prodotto,))        movimentazioni = cursor.fetchall()        cursor.close()        conn.close()        logger.info(f"Risposta API: {movimentazioni}")        return jsonify(movimentazioni)    except mysql.connector.Error as e:        logger.error(f"Errore nella richiesta: {e}")        return jsonify({'error': str(e)}), 500if __name__ == '__main__':    app.run(debug=False, host='0.0.0.0')
Hope this info sounds helpful. If needed i can share other info but just say me what you need to get the right command line for terminal
Thanks in advance

Statistics: Posted by morris1974 — Wed Mar 19, 2025 7:51 am



Viewing all articles
Browse latest Browse all 8015

Trending Articles