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

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)

Leave a Comment