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

六月ゝ 毕业季﹏ 提交于 2019-12-05 08:38:49

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)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!