dimanche 26 mars 2023

How to generate random numbers with view functions of Python Flask?

I´m trying generate new random numbers with view functions in Python Flask, but the numbers are always the same in the same web session.

Here a simplified code version:

def random_expression():
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    operator = random.choice(["+", "-", "*", "/"])
    return f"{num1} {operator} {num2}"

class MyForm(FlaskForm):
    expression = IntegerField(label=random_expression(),default=None)
    

@app.route("/", methods=['GET','POST'])
def index():
    form = MyForm()
    return render_template("index.html",form=form)

It´s like the random_expression() was executed only once no matter how many times the view function index() is called.




Aucun commentaire:

Enregistrer un commentaire