It’s easy to generate random numbers using the random module in Python. And we always do it when it’s required to send an OTP or a secret token to the user. The following code is the way we do it usually.

    import random
    random.randint(100000, 999999)

This should generate a 6 digit random OTP code.

But, according to the offical documentation of python secrets module, it’s not recommended to use the random module for generating passwords, account authentication, security tokens and related secrets. Instead secrets module is recommended. Which is designed for security or cryptography.

By replacing the code above with the secrets module we will have the following version of the code:

    import secrets
    secrets.SystemRandom().randrange(100000, 999999)

It uses the Operating System to get the most random number possible. Which uses high-entropy seeds to generate the random numbers.

Basically, the higher the entropy of the seed/key used to the generate the random number the more secure it gets.

And, the Operating System can provide the best high-entropy seeds as it can guess entropy based on the most random things like: the time between the key strokes on the keyboard, number of the running processes, CPU usuage percentage etc.

It does not necessarily mean that currently the Operating System is using exactly the random events that I have mentioned. It can be many other things. I just gave some examples of highly random events that an Operating System can find.

So, it is best to use the secrets module instead of random module for critical data like passwords, OTP, Tokens etc.