0

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?

Sd Junk
  • 272
  • 3
  • 15
  • Have already tried the solution present over here https://stackoverflow.com/questions/24892035/how-can-i-get-the-named-parameters-from-a-url-using-flask? – Tajinder Singh May 25 '22 at 14:09
  • @TajinderSingh I have just tried and it is not working. From what I understand in the thread you shared, the id could be retrieved that way if it were an URL parameter. But in my case the whole url, which I need to use in the redirected url, is appended to `/dash/monitoring` . Instead, I want it to be appended to `/home/dash/monitoring` – Sd Junk May 25 '22 at 14:51

2 Answers2

2

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 :)

ShivaGaire
  • 2,283
  • 1
  • 20
  • 31
0

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.

NoNameAv
  • 423
  • 2
  • 14