Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible for Flask to redirect with parameters?

I have two apps which are both launched by Flask, app1 and app2. In app2, I need to redirect to a url defined in app1 and pass a parameter(I need logged_in in the template).

If it was in the same app, I can do this by

from flask import Flask, render_template, redirect, url_for

app1 = Flask(__name__)


@app1.route('/')
def index():
   return render_template('index.html', logged_in=False)

@app1.get('/login')
def login():
   return redirect(url_for('index', logged_in=True))

However, I cannot do this in app2, let’s say.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from flask import Flask, redirect

app2 = Flask(__name__)

@app2.get('/login')
def login():
   return redirect('http://localhost:5000', logged_in=True) # this is not allowed.

Anyone has an idea? Thanks in advance.

>Solution :

You can use a query parameter when redirecting:

@app2.get('/login')
def login():
   return redirect('http://localhost:5000?logged_in=1')

And on the localhost server you can use Javascript to change the page based on the query param:

const urlParams = new URLSearchParams(window.location.search);
const loggedIn = urlParams.get('logged_in') == '1';
alert(loggedIn);

Or, if the localhost server is also running Flask, you can get the query params like so:

from flask import request

@app.route('/')
def root():
    logged_in = request.args.get('logged_in') == '1'
    return render_template('index.html', logged_in=logged_in)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading