mardi 8 septembre 2020

assignement of variable ignore after db.commit() in an if condition

I'm trying to write a web app with Flask. I wrote a in HTML page and this form use POST method for send data to a python function.

HTML code:

<form method="POST" action="">
                <div class="form-group">
                  <label for="food-name">Food Name</label>
                  <input type="text" class="form-control" name="food-name" id="food-name" placeholder="Food Name">
                </div>
                <div class="form-group">
                  <label for="protein">Protein</label>
                  <input type="number" class="form-control" name="protein" id="protein" placeholder="Protein">
                </div>
                <div class="form-group">
                  <label for="carbohydrates">Carbohydrates</label>
                  <input type="number" class="form-control" name="carbohydrates" id="carbohydrates" placeholder="Carbohydrates">
                </div>
                <div class="form-group">
                  <label for="fat">Fat</label>
                  <input type="number" class="form-control" name="fat" id="fat" placeholder="Fat">
                </div>
                <button type="submit" class="btn btn-primary">Add</button>
              </form>

Python function in my flask app:

'''

@app.route('/food', methods=['GET', 'POST'])

def food(): db = get_db()

if request.method == 'POST':
    name = request.form['food-name']
    protein = int(request.form['protein'])
    carbohydrates = int(request.form['carbohydrates'])
    fat = int(request.form['fat'])

    calories = protein * 4 + carbohydrates * 4 + fat * 9
    
    db.execute('INSERT INTO food (name, protein, carbohydrates, fat, calories) VALUES (?,?,?,?,?)', \
        [name, protein, carbohydrates, fat, calories])
    db.commit()


    cur = db.execute('SELECT * FROM food')
    results = cur.fetchall()

return render_template('add_food.html', results=results)

'''

And the python function return a HTML list of data stored in database, using a python loop embedded in the HTML code that uses the results variable as a condition :

<div class="page-header"></div>
              

But the variable results after condition if is not assigned and python raise UnboundLocalError: local variable 'results' referenced before assignment. I suppose it's fault to db.commit() who should act like break key word.

what do you think ? there is an error in the code ?

Thank you very much




Aucun commentaire:

Enregistrer un commentaire