0

I've come across this block of code where the model script is handling token verification:

def encode_auth_token(self, user_id):
    try:
        payload = {
               'exp': datetime.datetime.utcnow() + datetime.timedelta(
                    days=current_app.config.get('TOKEN_EXPIRATION_DAYS'), \
                    seconds=current_app.config.get('TOKEN_EXPIRATION_SECONDS')),
               'iat': datetime.datetime.utcnow(),
               'sub': user_id
        }
       
       return jwt.encode(payload, current_app.config.get('SECRET_KEY'), algorithm='HS256')
   except Exception as e:
       return e

@staticmethod
def decode_auth_token(token):
   try:
       return jwt.decode(token, current_app.config.get('SECRET_KEY'))
   except jwt.ExpiredSignatureError:
       return 'Signature expired. Please log in again.'
   except jwt.InvalidTokenError:
       return 'Invalid token. Please log in again.'

My question to this block of code is why decode_auth_token method needs to be a static method whereas encode_auth_token doesn't need to be ?

Mark
  • 1,385
  • 3
  • 16
  • 29
  • 2
    Does this answer your question? [What is the advantage of using static methods in Python?](https://stackoverflow.com/questions/2438473/what-is-the-advantage-of-using-static-methods-in-python) – mkrieger1 Jul 24 '20 at 09:17
  • Neither of these *need* to be either. Honestly, you'd have to ask whoever wrote the code. But, really all you can say is *because that is what whoever designed the API of that class decided it to be* – juanpa.arrivillaga Jul 24 '20 at 09:18
  • 2
    Both can be a staticmethod since they do not use `self`. – Klaus D. Jul 24 '20 at 09:19
  • Actually, both of them could be static since they don't use `self`. At the same time, there's nothing wrong to make them both plain instance methods. – Gevorg Davoian Jul 24 '20 at 09:20
  • @KlausD. the `encode_auth_token` method does. It needs access to model's ID attribute. – Mark Jul 24 '20 at 09:21
  • `encode_auth_token` can be staticmethod as well as I dont see any usages of the instance `self` – vestronge Jul 24 '20 at 09:21
  • @mkrieger1 So my understanding is that the `decode_auth_token` method was made a static method because it doesn't need to access any of the model's attribute unlike the first method. Nice. – Mark Jul 24 '20 at 09:23
  • @KlausD. You were right. The ID argument is being passed in from elsewhere hence it can be a static method too. Unittests passed. – Mark Jul 24 '20 at 09:27

0 Answers0