Redirecting to Url in Flask

Redirecting to URL in Flask

You have to return a redirect:

import os
from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def hello():
return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)

See the documentation on flask docs. The default value for code is 302 so code=302 can be omitted or replaced by other redirect code (one in 301, 302, 303, 305, and 307).

Redirecting in Flask with path from url

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

flask: redirecting a user to a particular section of the html page

you can try use id in your html simply add an id to the form then in your url add an #myFormId, if you'r using url_for do this

redirect(url_for("index")+"#myFormId")

also check this too.

Internal Redirect in Flask

You should use the Post-Redirect-Get pattern.

from flask import Flask, redirect, request, render_template
app = Flask("the_flask_module")

@app.route('/', methods=["GET", "POST"])
def post_redirect_get():
if request.method == "GET":
return render_template("post_redirect_get.html")
else:
# Use said data.
return redirect("target", code=303)

@app.route("/target")
def target():
return "I'm the redirected function"

app.run(host="0.0.0.0", port=5001)

And if you want to pass data to the target function (like that token) you can use the session object to store it

So that would break down something like

@app.route('/register', methods=['PUT'])
def register():
username = request.form.get('username')
password = request.form.get('password')
if username is None or password is None:
abort(400) # missing parameters

user = User.query.filter_by(username=username).first()
if user:
abort(400) # user exists
else:
user = User(user=user)
user.hash_password(password)
db.session.add(user)
db.session.commit()

# How do we generate a token?
redirect("login_success", code=307)

@app.route("login_success", methods=["GET", "POST"])
@jwt_required()
def login_success():
return "Redirected Success!"

Edit:
I haven't used Flask-JWT before and didn't know about the post requirement. But you can tell Flask to redirect with the current method used (rather than a get request) by passing the redirect function code=307.. Hopefully that solves your extended problem.

Flask redirect without url params

It seems like token is a dict value. Perhaps you could try getting the value for token['token'] and then add it to the url, instead of putting the entire token dict in.

For example:


app.route("/downloadConf/<token>", methods=["GET"])
def downloadConf(token):
token_val = token['token']
url = f"http://{ipAddress}/api/1.0/conf/{token_val}"
redir = redirect(url)
return redir



Related Topics



Leave a reply



Submit