I am sending a POST request from one form with two inputs to a Flask route.
<form action = "http://localhost:5000/xyz" method = "POST">
<p>x <input type = "text" name = "x" /></p>
<p>y <input type = "text" name = "y" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
The Flask code is like this.
@app.route('/xyz', methods = ['POST', 'GET'])
def xyz():
if request.method == 'POST':
x = request.form["x"]
y = request.form["y"]
callonemethod(x,y)
return render_template('index.html', var1=var1, var2=var2)
#abc(x,y) #can i call abc() like this .i want to call abc() immediately, as it is streaming log of callonemethod(x,y) in console.
@app.route('/abc', methods = ['POST', 'GET'])
def abc():
callanothermethod(x,y)
return render_template('index.html', var1=var3, var2=var4)
#I want to use that x, y here. also want to call abc() whenever i call xyz()
How can I call one route from another route with parameters in Flask?
The decorator syntax is just a little syntactic sugar. This code block shows an example using our custom decorator and the @login_required decorator from the Flask-Login extension. We can use multiple decorators by stacking them.
Routing in Flask The route() decorator in Flask is used to bind an URL to a function. As a result when the URL is mentioned in the browser, the function is executed to give the result. Here, URL '/hello' rule is bound to the hello_world() function.
You have two options.
Option 1:
Make a redirect with the parameters that you got from the route that was called.
If you have this route:
import os
from flask import Flask, redirect, url_for
@app.route('/abc/<x>/<y>')
def abc(x, y):
callanothermethod(x,y)
You can redirect to the route above like this:
@app.route('/xyz', methods = ['POST', 'GET'])
def xyz():
if request.method == 'POST':
x = request.form["x"]
y = request.form["y"]
callonemethod(x,y)
return redirect(url_for('abc', x=x, y=y))
See also the documentation about redirects in Flask
Option 2:
It seems like the method abc
is called from multiple different locations. This could mean that it could be a good idea to refactor it out of the view:
In utils.py
from other_module import callanothermethod
def abc(x, y):
callanothermethod(x,y)
In app/view code:
import os
from flask import Flask, redirect, url_for
from utils import abc
@app.route('/abc/<x>/<y>')
def abc_route(x, y):
callanothermethod(x,y)
abc(x, y)
@app.route('/xyz', methods = ['POST', 'GET'])
def xyz():
if request.method == 'POST':
x = request.form["x"]
y = request.form["y"]
callonemethod(x,y)
abc(x, y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With