Sign and load URL-safe values
When you need to pass signed data through a URL, such as in a password reset link or an email confirmation token, the URLSafeSerializer ensures the resulting string uses only URL-safe characters. It produces a string consisting of alphanumeric characters, underscores, hyphens, and dots, which can be safely included in a query parameter or path segment without further encoding.
from itsdangerous import URLSafeSerializer
# Initialize the serializer with a fixed secret key
auth_serializer = URLSafeSerializer("secret-key")
# Define a small dictionary to be serialized
original_data = {"user_id": 42, "action": "reset_password"}
# Serialize the dictionary into a URL-safe string
signed_url_token = auth_serializer.dumps(original_data)
# Restore the original data from the signed string
loaded_data = auth_serializer.loads(signed_url_token)
# Verify that the restored data matches the original input
assert loaded_data == original_data
The URLSafeSerializer uses zlib compression for the payload and encodes the result using a URL-safe base64 variant. During the loads process, it validates the signature against the provided secret key before decoding and decompressing the data. If the signature is invalid or the data has been tampered with, the serializer raises a BadSignature exception.