I recently changed the format of my URL’s to have better readability and SEO. However, this will break my current URL’s. So I want to redirect them in flask.
My question is similar to this one here:
Redirecting an old URL to a new one with Flask micro-framework
However, the provided answer gave this:
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)
The problem is, the code gives a 500 error code.
KeyError: ‘/article/old-url’
Edit:
Full traceback error:
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'
3
Answers
as wrote Klaus above just add @route decorator to your methods like:
So, it looks like this issue,
is caused because the following dictionary
only has the child path.
To resolve this, one approach you can take is
This will end up performing the following which is in the dictionary
redirect_urls
.Here is how I managed it.