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

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


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')    ...


One way of handling this would be to make a and b global variables:

a = Noneb = None@app.route('/consulta',methods=['POST'])def consulta():    if request.method=='POST': #Si se han enviado datos        ...        global a, b        a, b = aa[0], aa[1]        ...

Now, every time consulta() gets called, the global values of a and b are replaced with new ones. Elsewhere in the program, you can do the same thing in order to get the most recently-set values of a and b.


Note that, if you're encountering this problem, you might want to reconsider why you need the values of a and b to act like this. Are they tied to the specific user who submitted the POST request? How are you using them in the other function, and when does the other function run relative to this one?

If you need to access the same information between various disconnected API calls, but you have a way (such as a token) to track which user is making the request, I would recommend using an actual database to store information.