Python 3.6+secretsfunction
secrets.token_urlsafe()
tokens
Returns a random URL-safe Base64 token, for password reset links, API keys and invitations.
Syntax
secrets.token_urlsafe(nbytes=None) -> str
The argument is a number of random bytes, and the string comes out about 1.3 times longer: token_urlsafe(16) gives 22 characters. The alphabet is letters, digits, '-' and '_' with no trailing '=', so the token goes into a URL without encoding. Strength depends on nbytes, not on the visible length.
Examples
import secrets
t = secrets.token_urlsafe(16)
print(len(t)) # → 22
print('=' in t, '+' in t, '/' in t) # → False False False
print(t) # → ? случайная строка
See also
Open in the full glossarydocs.python.orgReport an inaccuracy