Generate JWT Token with PyJWT

  • Share this:

Code introduction


This function generates a JWT token from the given data and secret key. It uses the encode function from the PyJWT library to create the token.


Technology Stack : PyJWT

Code Type : Function

Code Difficulty : Intermediate


                
                    
import jwt
import datetime
import random

def generate_token(data, secret_key):
    """
    Generates a JWT token from the given data and secret key.
    """
    expiration_time = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
    payload = {
        'data': data,
        'exp': expiration_time
    }
    token = jwt.encode(payload, secret_key, algorithm='HS256')
    return token                
              
Tags: