Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting an old URL to a new one with Flask micro-framework

I'm making a new website to replace a current one, using Flask micro-framework (based on Werkzeug) which uses Python (2.6 in my case).

The core functionality and many pages are the same. However by using Flask many of the previous URLs are different to the old ones.

I need a way to somehow store the each of the old URLs and the new URL, so that if a user types in an old URL they are simply forwarded to the new URL and everything works fine for them.



Does anybody know if this is possible in Flask?

Thank you in advance for your help :-)

like image 831
Jon Cox Avatar asked Sep 24 '10 17:09

Jon Cox


People also ask

How do I redirect a URL to another Flask?

Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected. statuscode sent to browser's header, defaults to 302.

How do I make a button action redirect to another page in Flask?

If you want your form to submit to a different route you can simply do <form action="{{ url_for('app. login') }}"> . If you just want to put a link to the page use the <a> tag. If you want to process the request and then redirect, just use the redirect function provided by flask.

What is the difference between Render_template and redirect?

redirect returns a 302 header to the browser, with its Location header as the URL for the index function. render_template returns a 200, with the index. html template returned as the content at that URL.


2 Answers

Something like this should get you started:

from flask import Flask, redirect, request

app = Flask(__name__)

redirect_urls = {
    'http://example.com/old/': 'http://example.com/new/',
    ...
}

def redirect_url():
    return redirect(redirect_urls[request.url], 301)

for url in redirect_urls:
    app.add_url_rule(url, url, redirect_url)
like image 123
Radomir Dopieralski Avatar answered Nov 14 '22 22:11

Radomir Dopieralski


Another way you can do this is to change the handler for the old URL to simply redirect explicitly.

from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/new')
def new_hotness():
    return 'Sizzle!'

@app.route('/old')
def old_busted():
    return redirect(url_for('new_hotness'))

If you already have a handler for the old URL, then you might find the easiest thing to do is the above, i.e. just replacing the body with:

return redirect(url_for('new_hotness'))

Radomir's answer may be preferable especially if you have a lot of old-new URL mappings, however.

like image 24
Stephen J. Avatar answered Nov 14 '22 22:11

Stephen J.