Sign and load URL-safe values
To sign and verify data for use in URLs, itsdangerous provides the URLSafeSerializer class. This class ensures that the resulting string contains only characters safe for URL transmission—specifically alphanumeric characters, underscores, hyphens, and dots—by applying base64 encoding and optional zlib compression to the signed payload.
The URLSafeSerializer requires a secret key for signing. The dumps method serializes a Python object into a signed, URL-safe string, while the loads method verifies the signature and restores the original object.
from itsdangerous import URLSafeSerializer
# Initialize the serializer with a fixed secret key
auth_serializer = URLSafeSerializer(b"secret-key-for-signing")
# Define a small dictionary to serialize
original_data = {"user_id": 42, "role": "admin"}
# Serialize the dictionary to a signed, URL-safe string
signed_url_string = auth_serializer.dumps(original_data)
# Restore the original dictionary from the signed string
restored_data = auth_serializer.loads(signed_url_string)
# Verify that the restored data matches the original input
assert restored_data == original_data
assert restored_data["user_id"] == 42
When using URLSafeSerializer, the loads method will raise a BadSignature exception if the data has been tampered with or if the secret key does not match. If the payload is malformed or cannot be base64 decoded, it raises a BadPayload exception. These behaviors ensure that only data signed by the application can be successfully processed.