Secret Key generation for Django and Flask

Secret Key generation for Django and Flask

Both Django and Flask rely on SECRET_KEY to generate things like session IDs, cookies etc. Here is a safe way to generate them. Note that this relies on the secrets module introduced in Python 3.6 and onwards.

From the Python docs:

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particular, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

>>> import secrets
>>> secrets.token_urlsafe(16)
'AFzuAgp6gjoUkRZnuJwAdQ'
>>> secrets.token_hex(16)
'9df31cad3eb2f66386575da6dd6641ae'
>>>

I usually prefer the second option. token_hex.