Redirecting to URL in Flask
--
Track title: CC M Beethoven - Piano Sonata No 3 in C 3
--
Chapters
00:00 Question
00:37 Accepted answer (Score 513)
01:22 Answer 2 (Score 133)
01:54 Answer 3 (Score 48)
03:11 Answer 4 (Score 22)
03:55 Thank you
--
Full question
https://stackoverflow.com/questions/1434...
Accepted answer links:
[the documentation on flask docs.]: https://flask.palletsprojects.com/api/#f...
Answer 2 links:
[example in the documentation]: http://flask.pocoo.org/docs/quickstart/#...
Answer 3 links:
[Flask API Documentation]: https://flask.palletsprojects.com/en/2.0...
Answer 4 links:
[here]: http://flask.pocoo.org/docs/0.12/quickst...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #redirect #flask
#avk47
ACCEPTED ANSWER
Score 543
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)
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).
ANSWER 2
Score 140
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def hello():
return redirect(url_for('foo'))
@app.route('/foo')
def foo():
return 'Hello Foo!'
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)
Take a look at the example in the documentation.
ANSWER 3
Score 48
From the Flask API Documentation (v. 2.0.x):
flask.redirect(
location,code=302,Response=None)Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.
Parameters:
location– the location the response should redirect to.code– the redirect status code. defaults to 302.Response(class) – a Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified.
ANSWER 4
Score 10
flask.redirect(location, code=302)
Docs can be found here.