Reputation: 157
I'm writing a python function to validate a token from an email. In the email, there is a url with the endpoint of it. I have two url parameters, the token and email address. In my endpoint I have to check :
I choose to wrap all those checks in a try except
block, I will always return the same error "invalid token" so I don't have to precisely check individual error. I used the function assertFalse
and assertEqual
that will raise an exception if it's not correct.
try:
# pull from url
email = request.GET['email']
value_token = request.GET['token']
# test if valid
token = EmailValidationToken.objects.get(token=value_token)
assertFalse(token.consumed)
assertEqual(email, token.user.email)
assertFalse(token.is_expired())
except:
pass # return error
I like the way I did it because it's super clean. Is it a good practice ? Is there other solution for this problem ?
Upvotes: 1
Views: 1443
Reputation: 49318
No, using assert
for control flow rather than debugging is poor practice, because assertions can be turned off. Just use an ordinary if
statement.
# pull from url
email = request.GET['email']
value_token = request.GET['token']
# test if valid
token = EmailValidationToken.objects.get(token=value_token)
if token.consumed or email != token.user.email or token.is_expired():
pass # return error
If you absolutely insist on controlling your program's flow by raising an error (which is a valid thing to do in some cases), do so with raise
, e.g. if condition: raise TypeError
.
Upvotes: 6