Last active
October 10, 2018 20:09
-
-
Save pawl/762876a1770e0d2593b6 to your computer and use it in GitHub Desktop.
Redirecting Within A Helper Function - Flask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, redirect | |
from werkzeug.routing import RoutingException, HTTPException | |
app = Flask(__name__) | |
@app.route('/') | |
def hello_world(): | |
def helper_function(): | |
# Attempt #1 | |
# this obviously won't work: return redirect('www.google.com') | |
# the program would just return 'Hello World!' | |
# Attempt #2 | |
# THIS IS PERMANENT!: raise RequestRedirect('example2') | |
# your browser will cache the status 301 and ALWAYS redirect | |
# explanation: http://stackoverflow.com/a/16371787/1364191 | |
# Attempt #3 | |
class RequestRedirect(HTTPException, RoutingException): | |
"""Raise if the map requests a redirect. This is for example the case if | |
`strict_slashes` are activated and an url that requires a trailing slash. | |
The attribute `new_url` contains the absolute destination url. | |
The attribute `code` is returned status code. | |
""" | |
def __init__(self, new_url, code=301): | |
RoutingException.__init__(self, new_url) | |
self.new_url = new_url | |
self.code = code | |
def get_response(self, environ): | |
return redirect(self.new_url, self.code) | |
raise RequestRedirect('example3', code=302) | |
helper_function() | |
return 'Hello World!' | |
@app.route('/example2') | |
def example2(): | |
return 'Example 2' | |
@app.route('/example3') | |
def example3(): | |
return 'Example 3' | |
if __name__ == '__main__': | |
app.run(host="0.0.0.0", port=9999, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the example, super helpful!