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)
In my code we firs import
redirectandurl_for.We create 2 routes
indexandadmin.In
indexroute we output a simple response with the named passed to the url. So if we getexample.com/Johnit will outputHello John!.In
adminroute we redirect the user toindexroute because it's not the admin (This is a simple example that can you can model with what you want). Theindexroute needs a name so we pass inside theurl_forfunction some context so it can desplay the name.
