Reputation: 1639
I'm writing a very simple flask app (a URL shortener) that should be able to redirect certain requests to other arbitrary domains. However, I am running into problems with the redirection. This stripped-down version, for example, doesn't work:
from app import app, db
from flask import abort, redirect
@app.route('/')
def index():
return "Hello, world"
@app.route('/favicon.ico')
def favicon():
abort(404)
@app.route('/<slug>')
def redirect(slug):
return redirect('http://google.com/')
Perhaps naively, I expected this to redirect to google.com, but instead the redirect seems to get "captured" by Flask, and it tries to route the redirected URL back through the redirect handler (e.g. redirect(slug="http://google.com/")
) until it eats all the stack space through recursion and errors out. I can't seem to figure out why this would happen, or how to work around it, but I'd really appreciate a pointer in the right direction.
Upvotes: 1
Views: 3640
Reputation: 67509
The problem is in this function:
@app.route('/<slug>')
def redirect(slug):
return redirect('http://google.com/')
You named the function redirect()
, so in the scope of the function when you call return redirect(...)
this is interpreted as a recursive call because the view function shadows Flask's function of the same name. And the URL that you pass is mapped to the slug
argument in the recursive call.
Change the name of the view function from redirect()
to something else and your code will work just fine.
Upvotes: 5