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 data must be encoded into a format that is safe for web browsers and servers to handle. The URLSafeSerializer class in itsdangerous provides this functionality by serializing Python objects into a compact, URL-safe string using base64 encoding and optional zlib compression.
The following example demonstrates how to initialize a URLSafeSerializer with a secret key, serialize a dictionary into a signed string, and then verify and restore the original data.
from itsdangerous import URLSafeSerializer
# Initialize the serializer with a fixed secret key.
# This key is used to sign the data and verify it later.
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 signed string.
# URLSafeSerializer uses JSON for serialization and zlib for compression by default.
signed_string = serializer.dumps(original_data)
# Restore the data from the signed string.
# This step verifies the signature to ensure the data has not been tampered with.
loaded_data = serializer.loads(signed_string)
# Assert that the restored data is exactly equal to the original dictionary.
assert loaded_data == original_data
The URLSafeSerializer ensures that the resulting string consists only of alphanumeric characters, underscores, hyphens, and dots. During the dumps process, the URLSafeSerializerMixin.dump_payload method automatically applies zlib compression if the compressed result is smaller than the original JSON representation. When loads is called, URLSafeSerializerMixin.load_payload detects the compression (indicated by a leading dot) and decompresses the data before returning the original Python object.