Reputation: 45
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!!!
Upvotes: 3
Views: 3709
Reputation: 448
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')
...
Upvotes: 5
Reputation: 24721
One way of handling this would be to make a
and b
global variables:
a = None
b = 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.
Upvotes: 4