'Rewrite a URL with Flask

Is it possible to rewrite a URL with Flask e.g. if a POST request is received via this route:

@app.route('/', methods=['GET','POST'])
def main():
    if request.method == 'POST':
        #TODO: rewrite url to something like '/message'
        return render_template('message.html')
    else:
        return render_template('index.html')

I'm aware I can use a redirect and setup another route but I prefer to simply modify the url if possible.



Solution 1:[1]

You can call your route endpoint functions from another routes:

# The “target” route:
@route('/foo')
def foo():
    return render_template(...)

# The rewrited route:
@route('/bar')
def bar():
    return foo()

You can even access g etc. This approach can be also used when the Flask's routing facilities cannot do something that you want to implement.

Solution 2:[2]

This is actual solution to this problem (but maybe a dirty hack):

def rewrite(url):
    view_func, view_args = app.create_url_adapter(request).match(url)
    return app.view_functions[view_func](**view_args)

We invoke the URL dispatcher and call the view function.

Usage:

@app.route('/bar')
def the_rewritten_one():
    return rewrite('/foo')

Solution 3:[3]

from flask import Flask, redirect, url_for


app = Flask(__name__)
@app.route("/")
def home():
    return "hello"

@app.route("/admin"):
def admin():
    return redirect(url_for("#name of function for page you want to go to"))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jiwopene
Solution 2 jiwopene
Solution 3 Dan