How to Generate Random Tokens (UUID & Hex) in Python
In this tutorial, we will learn how to generate random UUID (Universally unique identifier) and hex tokens in Python using the secrets
package. Since we are using the secrets
package, the randomness of the tokens will be cryptographically secure.
Hex Strings
To generate hexadecimal tokens, import the secrets
package, then use the .token_hex()
function, passing the length of the hex string to create as the first argument.
import secrets
token = secrets.token_hex(32)
print(token)
d94c722648da4716d6ddf375b7031fc13406bbb32c6498fb9adaecd95842415c
UUID Strings
To generate a UUID, import the uuid
package and use the .uuid4()
function like this:
import uuid
string = uuid.uuid4()
print(string)
720f64dd-1b0d-4d4e-ac35-105aa1cc79a2