You can download this code by clicking the button below.
This code is now available for download.
This function generates a JWT token using the HS256 algorithm, which includes the user ID and expiration time.
Technology Stack : PyJWT
Code Type : Function
Code Difficulty : Intermediate
import jwt
import datetime
def generate_token(user_id, secret_key):
# Generate a JWT token for a given user ID and secret key
payload = {
'user_id': user_id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) # Token expires in 1 hour
}
token = jwt.encode(payload, secret_key, algorithm='HS256')
return token