Paul's Programming Notes     Archive     Feed     Github

Redirecting From Within Helper Functions - Flask

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)
view raw redirect.py hosted with ❤ by GitHub