How can we call one route from another route with parameters in Flask?

Issue

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?

Solution

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)

Answered By – matyas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published