python decorator

The Power of Python Decorators

At their core, Python’s decorators allow you to extend and modify the behavior of a callable (functions, methods, and classes) without permanently modifying the callable itself.

Any sufficiently generic functionality you can tack on to an existing class or function’s behavior makes a great use case for decoration. This includes the following:

  • logging
  • enforcing access control and authentication
  • instrumentation and timing functions
  • rate-limiting
  • caching and more

Sure, decorators are relatively complicated to wrap your head around for the first time, but they’re a highly useful feature that you’ll often encounter in third-party frameworks and the Python standard library. Explaining decorators is also a make or break moment for any good Python tutorial. I’ll do my best here to introduce you to them step by step.

When you create a big python application, you can began to run into challenges with longer scripts that extended beyond the expiration of a single JWT.

To elegantly solve this, You can use decorators to check the token’s expiration and request a new token if necessary. This article goes over the framework I set up so that you can apply a similar mechanism in your own scripts.

Setting the Scene


import time
import requests

class myAPI():
    host = None
    key = None
    secret = None
    access_token = None
    access_token_expiration = None

    def __init__(self,host,key,secret):
        # the function that is executed when
        # an instance of the class is created
        pass

    def getAccessToken(self):
        # the function that is 
        # used to request the JWT
        pass

    class Decorators():
        @staticmethod
        def refreshToken(decorated):
            # the function that is used to check
            # the JWT and refresh if necessary
            pass

Our class will work by requiring the fields necessary to request the JWT. Without access, there is nothing more our class will do.

When I was creating a one script, which uses JWT for authentication, I began to run into challenges with longer scripts that extended beyond the expiration of a single JWT.

To elegantly solve this, I used decorators to check the token’s expiration and request a new token if necessary. This article goes over the framework I set up so that you can apply a similar mechanism in your own scripts.

Setting the Scene


To get started, I’ve outlined all the parts needed to set up our token-refreshing framework.