Sqids Python

repository·main·Indexed 19 days ago

https://github.com/sqids/sqids-python

A Python library for generating unique, short, and URL-safe IDs from non-negative integers. It provides the Sqids class to encode sequences of numbers into IDs and decode them back, with support for custom alphabets, minimum length requirements, and blocklists to avoid specific patterns.

Tokens
1.4K
Snippets
8
Records
9
Agent score
66%

What's inside sqids-python

  1. Understand when to use Sqids

    main
    • Generating IDs for public URLs (e.g., link shortening).
    • Generating IDs for internal systems (e.g., event tracking).
    • Decoding IDs for quicker database lookups (e.g., by primary keys).

    When NOT to use Sqids

    • Sensitive data: This is not an encryption library; do not use it to hide sensitive information.
    • User IDs: Because IDs can be decoded, they may reveal information like total user counts.
  2. Encode and decode numbers with Sqids

    main

    Use sqids.encode() to generate a short, URL-safe ID from a list of non-negative integers. Use sqids.decode() to convert an ID back into its original list of numbers.

    Important Note on Canonicity: Due to the algorithm's design, multiple different IDs can decode back into the same sequence of numbers. If your system requires canonical IDs, you must manually re-encode the decoded numbers and verify that the resulting ID matches the original input.

    sqids = Sqids()
    id = sqids.encode([1, 2, 3]) # "86Rf07"
    numbers = sqids.decode(id) # [1, 2, 3]
  3. Configure Sqids with min_length, alphabet, and blocklist

    main

    The Sqids constructor accepts several configuration options to customize ID generation:

    • min_length: An integer that enforces a minimum length for generated IDs, providing more uniform ID lengths.
    • alphabet: A string used to randomize the output. Providing a custom alphabet changes the generated IDs.
    • blocklist: A list of strings representing specific sequences that should be prevented from appearing anywhere in the auto-generated IDs (useful for avoiding profanity or specific patterns).
    # Enforce a minimum length
    sqids = Sqids(min_length=10)
    id = sqids.encode([1, 2, 3])
    
    # Use a custom alphabet
    sqids = Sqids(alphabet="FxnXM1kBN6cuhsAvjW3Co7l2RePyY8DwaU04Tzt9fHQrqSVKdpimLGIJOgb5ZE")
    id = sqids.encode([1, 2, 3])
    
    # Use a blocklist to prevent specific strings
    sqids = Sqids(blocklist=["86Rf07"])
    id = sqids.encode([1, 2, 3])
  4. Initialize the Sqids class

    main

    The Sqids class is the main entry point for generating and parsing IDs. You can initialize it with a custom alphabet, a minimum ID length, and a blocklist of words to avoid.

    Initialization Parameters

    • alphabet (str): A string of unique characters used for encoding. Must be at least 3 characters long and cannot contain multibyte characters (must be ASCII).
    • min_length (int): The minimum length of the generated IDs. Must be between 0 and 255.
    • blocklist (List[str]): A list of strings that should not appear in the generated IDs. Words shorter than 3 characters are ignored.

    Validation Errors

    • ValueError: Raised if the alphabet contains multibyte characters, is shorter than 3 characters, contains duplicate characters, or if min_length is outside the 0-255 range.
    • TypeError: Raised if min_length is not an integer.
    from sqids import Sqids
    
    # Using default settings
    sqids = Sqids()
    
    # Using custom settings
    sqids = Sqids(
        alphabet="abcdefghijklmnopqrstuvwxyz1234567890",
        min_length=5,
        blocklist=["bad", "word"]
    )
  5. Encode numbers into Sqids

    main

    Use the encode method to convert a sequence of integers into a unique, URL-friendly string ID.

    • Input: A Sequence[int] (e.g., a list or tuple of integers).
    • Output: A str representing the encoded ID.
    • Constraints: All numbers must be non-negative and less than or equal to sys.maxsize.
    • Empty Input: If an empty sequence is provided, it returns an empty string "".

    Errors

    • ValueError: Raised if any number in the sequence is negative or exceeds sys.maxsize.
    from sqids import Sqids
    
    sqids = Sqids()
    ids = sqids.encode([1, 2, 3])
    print(ids)  # Example output: "k39v7"
  6. Decode Sqids into numbers

    main

    Use the decode method to convert a Sqids string ID back into its original sequence of integers.

    • Input: A str (the encoded ID).
    • Output: A List[int] containing the original numbers.
    • Invalid IDs: If the ID contains characters not present in the alphabet used for encoding, or if the ID is empty, it returns an empty list [].
    from sqids import Sqids
    
    sqids = Sqids()
    numbers = sqids.decode("k39v7")
    print(numbers)  # Example output: [1, 2, 3]