Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable from a function in another function, with flask

Im using Flask for making a website.

@app.route('/consulta',methods=['POST'])
def consulta():
    if request.method=='POST': #Si se han enviado datos
        dia = request.form['dia'] #Obtenemos los datos del formulario
        videobeam = request.form['videobeam']
        tablero = request.form['tablero']
        hora = request.form['hora']
        aa = darHora(hora)

        a = aa[0] #<<<<<----- HERE IS PROBLEM
        b = aa[1] #<<<<<<- HERE IS PROBLEM


        cursor = db.connection.cursor()
        cursor.execute("SELECT * FROM salones WHERE {0}=1 AND videobeam = '{2}' AND tablero = '{1}' AND `{3}` = 1 AND `{4}` = 1".format(dia,videobeam,tablero,a,b)) 

        #Buscamos que coincidan con la base de datos, se pregunta por el dia de disponibilidad, si tiene videobeam y tablero
        data = cursor.fetchall() #Se obtiene en una lista
        cursor.close() #Se cierra la conexión
        return render_template('consulta.html', datos = data) #Se visualizará los resultados, y se pasa a data como parametro

I would like to use variables 'a' and 'b' from that function, in another function, becase they came from the input from the user in a form. The problem is that i cannot "return" them, because flask only allows me to return the render_template for that function.

Any idea ? Thank you!!!

like image 767
Sebastian Ospina Avatar asked Jun 12 '26 16:06

Sebastian Ospina


1 Answers

Assuming the other function is a view function associated with a different endpoint, you can simply pass these variables using Flask session. E.g.:

from flask import session

@app.route('/consulta',methods=['POST'])
def consulta():
    if request.method=='POST': #Si se han enviado datos
        dia = request.form['dia'] #Obtenemos los datos del formulario
        videobeam = request.form['videobeam']
        tablero = request.form['tablero']
        hora = request.form['hora']
        aa = darHora(hora)

        session['a'] = aa[0] #<<<<<----- HERE IS PROBLEM
        session['b'] = aa[1] #<<<<<<- HERE IS PROBLEM
        ...

 @app.route('/something')
 def user_parameters():
    a = session.get('a')
    b = session.get('b')
    ...
like image 164
vendrediSurMer Avatar answered Jun 15 '26 05:06

vendrediSurMer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!