### Install Sqids Python Package Source: https://github.com/sqids/sqids-python/blob/main/README.md This command installs the Sqids Python library using pip. Ensure you have Python and pip installed on your system. ```bash pip install sqids ``` -------------------------------- ### Sqids Python for Link Shortener Service Source: https://context7.com/sqids/sqids-python/llms.txt A practical example demonstrating the use of Sqids in a link shortener service. It shows how to initialize Sqids with production settings (minimum length and blocklist), encode database record IDs into short URLs, and decode short IDs back to their original record IDs for efficient database lookups. It also illustrates encoding multiple values for composite keys. ```python from sqids import Sqids import sys # Initialize with production settings sqids = Sqids( min_length=8, # Consistent length for professional appearance blocklist=["profane", "badword", "blocked"] # Custom blocklist ) # Example: Link shortener service class LinkShortener: def __init__(self): self.sqids = Sqids(min_length=8) self.database = {} # Simulated database def shorten_url(self, long_url: str, record_id: int) -> str: """Generate short ID from database record ID""" short_id = self.sqids.encode([record_id]) self.database[short_id] = long_url return f"https://short.link/{short_id}" def resolve_url(self, short_id: str) -> str: """Resolve short ID back to original URL""" if short_id in self.database: return self.database[short_id] return None def get_record_id(self, short_id: str) -> int: """Decode short ID to database record ID for lookup""" numbers = self.sqids.decode(short_id) return numbers[0] if numbers else None # Usage example shortener = LinkShortener() # Shorten URLs using database primary keys url1 = shortener.shorten_url("https://example.com/very/long/url/path", record_id=12345) url2 = shortener.shorten_url("https://example.com/another/long/url", record_id=67890) print(f"Shortened URL 1: {url1}") print(f"Shortened URL 2: {url2}") # Extract record ID for database lookup (faster than string-based lookup) short_id = "a1b2c3d4" # This is a placeholder, actual short_id will be generated by encode # To make this runnable, we need to use an actual generated short_id # For demonstration, let's assume short_id = url1.split('/')[-1] short_id_from_url1 = url1.split('/')[-1] record_id = shortener.get_record_id(short_id_from_url1) print(f"Record ID for {short_id_from_url1}: {record_id}") # Resolve back to original URL original_url = shortener.resolve_url(short_id_from_url1) print(f"Original URL for {short_id_from_url1}: {original_url}") # Multiple value encoding for composite keys sqids_multi = Sqids(min_length=10) user_id = 1001 post_id = 5523 timestamp = 1609459200 composite_id = sqids_multi.encode([user_id, post_id, timestamp]) print(f"Composite ID: {composite_id}") # Decoding composite ID decoded_values = sqids_multi.decode(composite_id) print(f"Decoded values: {decoded_values}") assert decoded_values == [user_id, post_id, timestamp] ``` -------------------------------- ### Configure Custom Alphabet for Sqids in Python Source: https://context7.com/sqids/sqids-python/llms.txt Demonstrates how to randomize Sqids ID output by providing a custom character set for encoding. Includes examples of standard encoding, custom alphabet encoding, uppercase-only alphabet, and validation checks for alphabet length, uniqueness, and character types. ```python from sqids import Sqids # Standard encoding sqids_default = Sqids() id_default = sqids_default.encode([1, 2, 3]) print(id_default) # Output: "86Rf07" # Custom alphabet for different output custom_alphabet = "FxnXM1kBN6cuhsAvjW3Co7l2RePyY8DwaU04Tzt9fHQrqSVKdpimLGIJOgb5ZE" sqids_custom = Sqids(alphabet=custom_alphabet) id_custom = sqids_custom.encode([1, 2, 3]) print(id_custom) # Output: "B4aajs" # Uppercase-only alphabet sqids_upper = Sqids(alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ") id_upper = sqids_upper.encode([1, 2, 3]) print(id_upper) # Output: "SXNZKL" # Alphabet validation - must have at least 3 unique characters try: sqids_invalid = Sqids(alphabet="ab") except ValueError as e: print(f"Error: {e}") # "Alphabet length must be at least 3" try: sqids_duplicate = Sqids(alphabet="aabbcc") except ValueError as e: print(f"Error: {e}") # "Alphabet must contain unique characters" try: sqids_multibyte = Sqids(alphabet="café") except ValueError as e: print(f"Error: {e}") # "Alphabet cannot contain multibyte characters" ``` -------------------------------- ### Initialize Sqids Constructor in Python Source: https://context7.com/sqids/sqids-python/llms.txt Initializes a Sqids instance with optional configurations for alphabet, minimum ID length, and blocklist filtering. It supports default settings or custom parameters for advanced usage. ```python from sqids import Sqids # Default configuration - uses standard alphabet and built-in blocklist sqids = Sqids() # Custom alphabet for randomized output sqids_custom = Sqids( alphabet="FxnXM1kBN6cuhsAvjW3Co7l2RePyY8DwaU04Tzt9fHQrqSVKdpimLGIJOgb5ZE" ) # Minimum length for uniform ID sizes sqids_min = Sqids(min_length=10) # Custom blocklist to prevent specific words sqids_blocklist = Sqids(blocklist=["86Rf07", "word2block"]) # Combined configuration sqids_full = Sqids( alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", min_length=8, blocklist=["badword", "blocked"] ) ``` -------------------------------- ### Configure Minimum ID Length for Sqids in Python Source: https://context7.com/sqids/sqids-python/llms.txt Shows how to set a minimum ID length for Sqids to create more uniform identifiers by adding padding. Contrasts the length and output of IDs generated with and without a minimum length configuration. ```python from sqids import Sqids # No minimum length sqids_default = Sqids() id1 = sqids_default.encode([1, 2, 3]) print(f"Length {len(id1)}: {id1}") # Output: "Length 6: 86Rf07" # With minimum length padding sqids_padded = Sqids(min_length=10) id2 = sqids_padded.encode([1, 2, 3]) print(f"Length {len(id2)}: {id2}") # Output: "Length 10: 86Rf07xd4z" ``` -------------------------------- ### Set Minimum ID Length with Sqids Python Source: https://context7.com/sqids/sqids-python/llms.txt Demonstrates how to set a minimum length for generated Sqids. IDs shorter than the specified minimum length will be padded. It also shows how invalid minimum length values (outside the 0-255 range) raise a ValueError. ```python from sqids import Sqids # Minimum length of 10 characters sqids_min10 = Sqids(min_length=10) id2 = sqids_min10.encode([1, 2, 3]) print(f"Length {len(id2)}: {id2}") # Minimum length of 20 characters sqids_min20 = Sqids(min_length=20) id3 = sqids_min20.encode([1, 2, 3]) print(f"Length {len(id3)}: {id3}") # All decode to the same numbers despite different lengths numbers = [1, 2, 3] # Assuming sqids_default and id1 are defined elsewhere for completeness # assert sqids_default.decode(id1) == numbers assert sqids_min10.decode(id2) == numbers assert sqids_min20.decode(id3) == numbers # Minimum length validation (0-255 range) try: sqids_invalid = Sqids(min_length=256) except ValueError as e: print(f"Error: {e}") try: sqids_negative = Sqids(min_length=-1) except ValueError as e: print(f"Error: {e}") ``` -------------------------------- ### Basic Encode and Decode with Sqids Python Source: https://github.com/sqids/sqids-python/blob/main/README.md Demonstrates the fundamental usage of the Sqids library in Python for encoding a list of numbers into a short ID and decoding it back. The `Sqids` class is imported and instantiated, then its `encode` and `decode` methods are used. ```python from sqids import Sqids sqids = Sqids() id = sqids.encode([1, 2, 3]) # "86Rf07" numbers = sqids.decode(id) # [1, 2, 3] ``` -------------------------------- ### Configure Blocklist in Sqids Python Source: https://context7.com/sqids/sqids-python/llms.txt Illustrates how to use blocklists to prevent specific words or patterns from appearing in generated Sqids. This includes using the default blocklist, an empty blocklist for no filtering, custom blocklists, and handling blocklist words shorter than 3 characters, which are ignored. ```python from sqids import Sqids # Default blocklist (built-in profanity filter) sqids_default = Sqids() id1 = sqids_default.encode([4572721]) print(id1) # Empty blocklist (no filtering) sqids_no_filter = Sqids(blocklist=[]) id2 = sqids_no_filter.encode([4572721]) print(id2) # Custom blocklist - block specific IDs sqids_custom = Sqids(blocklist=["86Rf07"]) id3 = sqids_custom.encode([1, 2, 3]) print(id3) # Verify all blocked variants decode correctly sqids_multi_block = Sqids(blocklist=["86Rf07", "se8ojk", "ARsz1p", "Q8AI49", "5sQRZO"]) assert sqids_multi_block.decode("86Rf07") == [1, 2, 3] assert sqids_multi_block.decode("se8ojk") == [1, 2, 3] assert sqids_multi_block.decode("ARsz1p") == [1, 2, 3] # Blocklist with multiple words sqids_complex = Sqids( blocklist=[ "JSwXFaosAN", # Block prefix "OCjV9JK64o", # Block substring "rBHf", # Block suffix ] ) id4 = sqids_complex.encode([1000000, 2000000]) print(id4) assert sqids_complex.decode(id4) == [1000000, 2000000] # Blocklist filtering by alphabet - words with incompatible characters are ignored sqids_filtered = Sqids( alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ", blocklist=["sxnzkl"] # Lowercase word filtered out ) id5 = sqids_filtered.encode([1, 2, 3]) print(id5) # Note: Blocklist words shorter than 3 characters are ignored sqids_short = Sqids(blocklist=["ab", "x"]) id6 = sqids_short.encode([0]) print(id6) ``` -------------------------------- ### Enforce Minimum ID Length with Sqids Python Source: https://github.com/sqids/sqids-python/blob/main/README.md Shows how to configure Sqids to generate IDs with a minimum specified length. This is achieved by passing the `min_length` argument during the `Sqids` class instantiation. Longer IDs are generated if necessary to meet the minimum length requirement. ```python from sqids import Sqids sqids = Sqids(min_length=10) id = sqids.encode([1, 2, 3]) # "86Rf07xd4z" numbers = sqids.decode(id) # [1, 2, 3] ``` -------------------------------- ### Decode Composite ID with Sqids Python Source: https://context7.com/sqids/sqids-python/llms.txt Demonstrates decoding a composite ID into multiple values using the sqids_multi decode function. This is useful when an ID represents multiple pieces of information. ```python user_id, post_id, timestamp = sqids_multi.decode(composite_id) print(f"Decoded: user={user_id}, post={post_id}, time={timestamp}") ``` -------------------------------- ### Blocklist Specific Words in Sqids Python IDs Source: https://github.com/sqids/sqids-python/blob/main/README.md Demonstrates how to prevent certain words or character sequences from appearing in generated Sqids. This is useful for maintaining brand safety or avoiding undesirable terms. The `blocklist` argument is passed as a list of strings during `Sqids` instantiation. ```python from sqids import Sqids sqids = Sqids(blocklist=["86Rf07"]) id = sqids.encode([1, 2, 3]) # "se8ojk" numbers = sqids.decode(id) # [1, 2, 3] ``` -------------------------------- ### Customize Alphabet for Randomized IDs in Sqids Python Source: https://github.com/sqids/sqids-python/blob/main/README.md Illustrates how to provide a custom alphabet to the Sqids library for generating randomized IDs. Using a custom alphabet can affect the appearance of the generated IDs and their mapping. The `alphabet` argument is passed during `Sqids` instantiation. ```python from sqids import Sqids sqids = Sqids(alphabet="FxnXM1kBN6cuhsAvjW3Co7l2RePyY8DwaU04Tzt9fHQrqSVKdpimLGIJOgb5ZE") id = sqids.encode([1, 2, 3]) # "B4aajs" numbers = sqids.decode(id) # [1, 2, 3] ``` -------------------------------- ### Decode IDs to Numbers in Python Source: https://context7.com/sqids/sqids-python/llms.txt Decodes a string identifier back into the original sequence of numbers using the Sqids library. It handles basic decoding, single numbers, large numbers, and ignores padding when minimum length is set. Also covers empty strings, invalid characters, and demonstrates a round-trip encoding/decoding process. ```python from sqids import Sqids sqids = Sqids() # Basic decoding numbers1 = sqids.decode("86Rf07") print(numbers1) # Output: [1, 2, 3] # Decode single number numbers2 = sqids.decode("Uk") print(numbers2) # Output: [1] # Decode large numbers numbers3 = sqids.decode("p9XzwBYu") print(numbers3) # Output: [1000000, 2000000] # Decoding with minimum length (padding is ignored) sqids_padded = Sqids(min_length=10) numbers4 = sqids_padded.decode("86Rf07xd4z") print(numbers4) # Output: [1, 2, 3] # Empty string returns empty list numbers5 = sqids.decode("") print(numbers5) # Output: [] # Invalid characters return empty list numbers6 = sqids.decode("invalid*chars!") print(numbers6) # Output: [] # Round-trip encoding and decoding original = [100, 200, 300] encoded = sqids.encode(original) decoded = sqids.decode(encoded) assert original == decoded # True ``` -------------------------------- ### Encode Numbers to IDs in Python Source: https://context7.com/sqids/sqids-python/llms.txt Encodes a sequence of non-negative integers into a unique string identifier using the Sqids library. Supports single or multiple numbers, large numbers, and handles empty inputs. It also demonstrates how sequential inputs produce non-sequential IDs and error handling for invalid inputs. ```python from sqids import Sqids sqids = Sqids() # Single number encoding id1 = sqids.encode([1]) print(id1) # Output: "Uk" # Multiple numbers encoding id2 = sqids.encode([1, 2, 3]) print(id2) # Output: "86Rf07" # Large numbers id3 = sqids.encode([1000000, 2000000]) print(id3) # Output: "p9XzwBYu" # Sequential inputs produce non-sequential IDs id4 = sqids.encode([0]) id5 = sqids.encode([1]) id6 = sqids.encode([2]) print(f"{id4}, {id5}, {id6}") # Output: "bM, Uk, gb" # With minimum length padding sqids_padded = Sqids(min_length=10) id7 = sqids_padded.encode([1, 2, 3]) print(id7) # Output: "86Rf07xd4z" # Empty input returns empty string id8 = sqids.encode([]) print(id8) # Output: "" # Error handling for out-of-range numbers try: sqids.encode([-1]) # Negative numbers not supported except ValueError as e: print(f"Error: {e}") ``` -------------------------------- ### Safe Encoding with Error Handling in Python Source: https://context7.com/sqids/sqids-python/llms.txt Implements a safe encoding function that handles potential ValueError exceptions during the encoding process. This prevents application crashes due to invalid input values, such as numbers outside the supported range. ```python import sys def safe_encode(numbers): try: return sqids.encode(numbers) except ValueError as e: print(f"Encoding error: {e}") return None result = safe_encode([sys.maxsize]) # Valid print(f"Max size encoded: {result}") result = safe_encode([sys.maxsize + 1]) # Invalid print(f"Out of range: {result}") ``` -------------------------------- ### Round-trip Verification for Data Integrity in Python Source: https://context7.com/sqids/sqids-python/llms.txt Provides a function to verify data integrity by ensuring that an encoded Sqids string can be decoded back to the original list of numbers. It raises a ValueError if the round-trip fails, indicating a potential issue with the encoding or data. ```python def verify_encoding(numbers): """Ensure encoded ID decodes back to original numbers""" encoded = sqids.encode(numbers) decoded = sqids.decode(encoded) if decoded == list(numbers): return encoded raise ValueError("Encoding verification failed") safe_id = verify_encoding([100, 200, 300]) print(f"Verified ID: {safe_id}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.