Reputation: 449
I'm reading Miguel Grindberg's great new book "Flask Web Development", and don't understand part of this code on page 107. . .
@auth.before_app_request
def before_request():
if current_user.is_authenticated() \
and not current_user.confirmed \
and request.endpoint[:5] != 'auth.':
return redirect(url_for('auth.unconfirmed'))
I do not understand what the purpose of the slice ([:5]) is in the line. . .
and request.endpoint[:5] != 'auth.':
Here's his explanation for the code. #3 is referring to the line in question.
"The before_app_request handler will intercept a request when three conditions are true: 1. A user is logged in (current_user.is_authenticated() must return True). 2. The account for the user is not confirmed. 3. The requested endpoint (accessible as request.endpoint) is outside of the authentication blueprint. Access to the authentication routes needs to be granted, as those are the routes that will enable the user to confirm the account or perform other account management functions."
My question is, why the slice ([:5])? To me it seems the code would match his explanation perfectly without the slice. He says the purpose is to catch any endpoint outside of "auth", so it seems to me the code should be. . .
and request.endpoint != 'auth.':
Any help would be GREATLY appreciated. Thanks.
Upvotes: 0
Views: 281
Reputation: 20739
request.endpoint
is a string. It has no knowledge about blueprints and views. The slice is there because request.endpoint
contains more than just 'auth.'
, for example 'auth.unconfirmed'
. This could also have been written as request.endpoint.startswith('auth.')
.
request.endpoint != 'auth.'
will always evaluate to true because there will never be an endpoint with that name. If you tried to evaluate url_for('auth.')
you'd get a BuildError
.
Upvotes: 0
Reputation: 12395
request.endpoint
holds data like auth.unconfirmed
or main.whatever
the code here is a check for the blueprint part (in this case"auth.")
after line
return redirect(url_for('auth.unconfirmed'))
was executed, this whole code block gets called again (request.endpoint having the value 'auth.unconfirmed', without the slice this would be a infinite loop)
Long story short: do not redirect if in auth blueprint
Concerning your comment: from the doc:
@before_app_request
Such a function is executed before each request, even if outside of a blueprint.
So after return redirect(url_for('auth.unconfirmed'))
the block is called again (new request), but now request.endpoint is the string 'auth.unconfirmed'. Then request.endpoint[:5] != 'auth.'
is false and then there is no further redirect (otherwise there would be the endless loop)
Upvotes: 3