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

Python • problem with flask app.py

$
0
0
Hello i wrote before for a project i managing for myself, i'd some issues with a double IP on

Code:

hostname -I
and i solved thanks to the community, now i got another problem.
I've making a installation of Apache server and mariaDB then i make an user for creating a database finally i did the app.py on flask for loading a web page locally loaded for the items inside the storage of my farm, long story short a web page which i can check everytime on the LAN for updating the items in the storage, the problem is that after few hours app.py it stop and consequently the web page go unreachable.
I using a raspberry pi3 with the last O.S. (i did the installation from RPIMager) the i

Code:

sudo apt update && sudo apt upgrade
and only later i start to install everything needed for the good working of the project, i also both a sd card 64gb sandisk used for home security cameras or dash cameras to flush away the problem of the writing many times and crashing.
i post here the app.py file (sorry if you see errors but as i wrote in the other thread i am a beekeeper and this is not my work i have to make this instead buy a software for the storage where the shop who is selling asked me enough euros to avoid it :) )

Code:

  GNU nano 7.2                                                 app.py                                                          from flask import Flask, render_template, jsonify, requestimport requestsimport loggingimport mysql.connector  # Importa la libreria per il databaseapp = Flask(__name__)# Configurazione del loggerlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# Configurazione del databasedb_config = {    'host': 'localhost',    'user': 'xxxxx',      'password': 'xxxxxxx',      'database': 'magazzino'}@app.route('/')def magazzino():    return render_template('magazzino.html')@app.route('/api/prodotti')def get_prodotti():    logger.info("Richiesta GET /api/prodotti")    try:        # Connessione al database        conn = mysql.connector.connect(**db_config)        cursor = conn.cursor(dictionary=True)        # Query per recuperare tutti i prodotti        cursor.execute("SELECT id, nome, quantita FROM prodotti")        prodotti = cursor.fetchall()        # Chiusura della connessione        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:        # Connessione al database        conn = mysql.connector.connect(**db_config)        cursor = conn.cursor(dictionary=True)        # Query per recuperare la quantità del prodotto        cursor.execute("SELECT quantita FROM prodotti WHERE id = %s", (id_prodotto,))        result = cursor.fetchone()        # Chiusura della connessione        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']        # Connessione al database        conn = mysql.connector.connect(**db_config)        cursor = conn.cursor()        # Query per aggiornare la quantità        cursor.execute("UPDATE prodotti SET quantita = %s WHERE id = %s", (quantita, id_prodotto))        conn.commit()        # Chiusura della connessione        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)}), 500if __name__ == '__main__':    app.run(debug=True, host='0.0.0.0')
Is there any error? why the app.py it stops. If needed i can as well post the html file or the php files i just do not wanna overwhelming the post and not putting some in confusion with three or four code more.
Thanks in advance to all for helping me and my wallet...yes off course and the technician which came for the organic certification who asked me this new step in my farm and he will have all he need next time he will come here
I've seen i got all wrote in italian but if needed i can change all in english for a easier reading

Statistics: Posted by morris1974 — Thu Mar 13, 2025 6:36 am



Viewing all articles
Browse latest Browse all 1225

Trending Articles