You can download this code by clicking the button below.
This code is now available for download.
This function generates a JWT token that includes data and an expiration time.
Technology Stack : PyJWT, datetime, random
Code Type : Authentication
Code Difficulty : Intermediate
import jwt
import datetime
import random
def generate_token(data, secret_key):
# Generate a token with a payload that includes an expiration time
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
# JSON representation of the code details
code_details = {
"type": "Authentication",
"hard": "中级",
"explain": "该函数生成一个JWT(JSON Web Token)令牌,该令牌包含数据和一个过期时间。",
"tench": "PyJWT, datetime, random",
"explain_en": "This function generates a JWT token that includes data and an expiration time.",
"tench_en": "PyJWT, datetime, random"
}
# Example usage
token = generate_token({"user_id": 123, "role": "admin"}, "your_secret_key")
print(token)