How to Generate Unique Auth Token in Python

In Python, you can use the secrets module to generate secure random numbers, which is specifically designed for cryptographic purposes and can generate random numbers suitable for cryptographic use. Here is an example of a Python function that emulates the functionality of the JavaScript function you provided:


import secrets
import string

def generate_token(length: int, options: dict = None) -> str:
if options is None:
options = {}

    uppercase = options.get('uppercase', True)
    lowercase = options.get('lowercase', True)
    numbers = options.get('numbers', True)

    charset = ''
    if uppercase:
        charset += string.ascii_uppercase
    if lowercase:
        charset += string.ascii_lowercase
    if numbers:
        charset += string.digits

    if not charset:
        raise ValueError('At least one character set must be selected.')

    token = ''.join(secrets.choice(charset) for _ in range(length))
    return token

# Example usage:

token = generate_token(16, {
'uppercase': True,
'lowercase': True,
'numbers': True
})
print("Generated token:", token)

In this Python function, generate_token accepts two parameters: length (the length of the token) and an options dictionary, which contains configurations for whether to include uppercase letters, lowercase letters, and numbers. Inside the function, a character set charset is constructed, and then the secrets.choice function is used to securely select random characters from charset. This process is repeated length times to generate a token of the desired length.

Please note that the secrets module was introduced in Python 3.6 and later, providing functions to generate secure random numbers suitable for cryptographic and security-related purposes. If you are using a version of Python below 3.6, you might need to use os.urandom or the random.SystemRandom class, but secrets is the preferred choice because it is specifically designed for cryptography.