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)



UUID Strings

To generate a UUID, import the uuid package and use the .uuid4() function like this:


import uuid

string = uuid.uuid4()