If you generate an API token or a temporary password in Python, reach for secrets and leave random alone.
import secrets
print(secrets.token_urlsafe(32)) # e.g. 'q0x8...' safe in URLs and .env files
print(secrets.token_hex(16)) # 32 hex characters
if secrets.compare_digest(given_token, stored_token):
print("ok")
The random module is built for simulations and games. Its output can be predicted once someone has seen enough of it. secrets uses the operating system’s secure random source, the same one /dev/urandom gives you.
The number you pass is bytes of randomness, not characters. token_urlsafe(32) gives 32 random bytes, encoded as about 43 characters of letters, digits, - and _. That alphabet means you can drop it into a URL, an environment file or a Docker Compose file without escaping anything.
I included compare_digest because it belongs with this. Comparing tokens with == can stop at the first wrong character, and in theory the timing leaks how much of a guess was right. compare_digest takes the same time either way. For a quick one off from the terminal, python3 -c 'import secrets; print(secrets.token_urlsafe(32))' works fine too.
Further reading: secrets module