我最近更改了URL的格式,以提高可读性和SEO。但是,这会破坏我当前的URL。所以我想将它们重定向到烧瓶中。
我的问题与这里的问题类似: Redirecting an old URL to a new one with Flask micro-framework
但是,提供的答案给出了这一点:
redirect_urls = {
'/article/old-url': '/article/new-url/id',
'/article/old-url-2': '/article/new-url-2/id',
'/article/old-url-3': '/article/new-url-3/id',
...
}
def redirect_url():
return redirect(redirect_urls[request.url], 301)
for url in redirect_urls:
app.add_url_rule(url, url, redirect_url)
问题是,该代码给出了500个错误代码。
KeyError:'/ article / old-url'
编辑:
完整回溯错误:
Exception on /article/old-url [GET]
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.4/dist-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/*****/mysite/flask_app.py", line 77, in redirect_url
return redirect(redirect_urls[request.url], 301)
KeyError: 'https://www.example.com/article/old-url'
答案 0 :(得分:1)
所以,看起来像这个问题,
File "/home/*****/mysite/flask_app.py", line 77, in redirect_url
return redirect(redirect_urls[request.url], 301)
KeyError: 'https://www.example.com/article/old-url'
是由于以下字典引起的
redirect_urls = {
'/article/old-url': '/article/new-url/id',
'/article/old-url-2': '/article/new-url-2/id',
'/article/old-url-3': '/article/new-url-3/id',
...
}
只有子路径。
要解决此问题,您可以采用的一种方法是
BASE_URL = 'https://www.example.com'
return redirect(redirect_urls[request.url.replace(BASE_URL, '')], 301)
这将最终执行字典redirect_urls
中的以下操作。
return redirect(redirect_urls['/article/old-url'], 301)
答案 1 :(得分:0)
如上面Klaus所写,只需将@route装饰器添加到您的方法中,例如:
@app.route('/article/old-url', methods=['GET'])
def redirect_url():
return redirect(redirect_urls[request.url], 301)