8

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.

  • Do you mean you want to change URL info in the POST message you get? – Stephen Lin Mar 25 '15 at 09:45
  • I was hoping to be able to change the URL that the user sees in the browser bar. Can that only be done on the clientside e.g. with JS or with a Flask redirect? –  Mar 25 '15 at 09:50

4 Answers4

0

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.

jiwopene
  • 3,077
  • 17
  • 30
0

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')
jiwopene
  • 3,077
  • 17
  • 30
-1

I think you could be interested in redirect behavior

from flask import Flask,redirect

then use

redirect("http://www.example.com", code=302)

see: Redirecting to URL in Flask

Community
  • 1
  • 1
head7
  • 1,373
  • 12
  • 12
  • 6
    That induces a new request to the server. Is there a way to actually do what was asked initially ? – gruvw Mar 08 '21 at 21:05
  • The OP specifically mentioned being aware that they could use rewrite, but asked if they could modify the URL *without* doing a redirect. – Aurelia Peters Mar 08 '22 at 23:43
-1
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"))
Dan
  • 1