Home > Back-end >  Redirecting in Flask with path from url
Redirecting in Flask with path from url

Time:05-26

I am running into a problem trying to redirect in Flask using the following:

 @views.route('/dash_monitoring/<path:url>')
 @login_required
 def monitoring_page(url):
     return redirect("/home/dash_monitoring/{}".format(url))

The url in <path:url> is in the format https://somesite.com/detail/?id=2102603 but when I try to print it in the function, it prints https://somesite.com/detail only without the id part,so it obviously redirects to /home/dash_monitoring/https://somesite.com/detail instead of /home/dash_monitoring/https://somesite.com/detail/?id=2102603.

What should I do so it keeps the id part and redirects to the right url?

CodePudding user response:

You can use request.url and imply string manipulation:

@views.route('/dash_monitoring/<path:url>')
@login_required
def monitoring_page(url):
    parsed_path = request.url.split('/dash_monitoring/')[1]
    #return the parsed path
    return redirect("/home/dash_monitoring/{}".format(parsed_path))

Alternatively, you can iterate through request.args for creating query string and construct path with args

@views.route('/dash_monitoring/<path:url>')
@login_required
def monitoring_page(url):
    query_string = ''
    for arg,value in request.args.items():
        query_string =f"{arg}={value}&"
    query_string=query_string[:-1] # to remove & at the end
    path=f"{path}?{query_string}"
    #return the parsed path
    return redirect(f"/home/dash_monitoring/{path}")

I hope this helps :)

CodePudding user response:

This has an easy solution, we use the url_for function:

from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/<name>')
def index(name):
     return f"Hello {name}!"

@app.route('/admin')
def admin():
     return redirect(url_for('index',name = 'John'))

if __name__ == '__main__':
     app.run(debug = True)
  1. In my code we firs import redirect and url_for.

  2. We create 2 routes index and admin.

  3. In index route we output a simple response with the named passed to the url. So if we get example.com/John it will output Hello John!.

  4. In admin route we redirect the user to index route because it's not the admin (This is a simple example that can you can model with what you want). The index route needs a name so we pass inside the url_for function some context so it can desplay the name.

  • Related