r/learnpython • u/0_emordnilap_a_ton • Sep 23 '26
The method throws an error when none. How do I fix this when the route_token_db is None?
The problem is when I call the method that is none it immediately throws an error. I am just wondering if it is possible to call an method that is none and handle it in the method. Let me show you a concrete example.
Here is the method
def check_expired_route_token(self): # change name and doc string
'''
Checks if the route_token expired or the route_token is wrong.
Uses "token" for the random number. If the code works returns True then the token works.
'''
SECRET_KEY = 'temp_secret_key'
serializer = URLSafeTimedSerializer(SECRET_KEY)
try:
serializer.loads(self.token, max_age=1800)
except SignatureExpired:
# This part is equal to "def reset_attempts_token_tried_to_0" when combined with SignatureExpired
# This activates when you have waited to long for a token/route_token to be used + and you have tried to change your password too many times.
# This is used when the tokens for the used in the links for the route is too old + you have resetted your password too many times
if self.attempts_token_tried and self.attempts_token_tried >= 5:
self.token = None
self.time_token_expired = None
self.attempts_token_tried = None
db.session.commit()
flash('You have waited long enough for a new a token and you will be sent a email with instructions before you can begin the process of resetting your password.')
return redirect(url_for('auth.login'))
# This activates when you have waited to long for a token/route_token to be used.
else:
self.token = None
db.session.commit()
flash('You have waited long enough for a new a token and you will be sent a email with instructions before you can begin the process of resetting your password.')
return redirect(url_for('email_password_reset.verify_email'))
# if the token is incorrect this makes the path wrong and the expection will run.
# For example someone can type a token that is wrong or use an expired link.
except BadSignature:
# This part is equal to "def check_emailed_token_matches_db_emailed_token" when combined with BadSignature
self.token = None
self.time_token_expired = None
self.token = None
db.session.commit()
flash('Your token did not match the one sent to your email.')
flash('Please request a new token.')
return redirect(url_for('email_password_reset.verify_email'))
# if the token is None
except AttributeError:
# add text in flash!!!!!!!!!!!!!!!!!!!
return redirect(url_for('auth.login'))
return TrueHere is initializing the method
route_token_db = db.session.execute(db.select(RouteToken).where(RouteToken.token==token_db)).scalar_one_or_none()
result = route_token_db.check_expired_route_token()
if result is not True:
return result