What is the standard method for generating a nonce in Python?

charliesneath picture charliesneath · Apr 8, 2011 · Viewed 26.2k times · Source

Can someone share the best practices for creating a nonce for an OAuth request in Python?

Answer

andruso picture andruso · Oct 30, 2016

For most practical purposes this gives very good nonce:

import uuid
uuid.uuid4().hex
# 'b46290528cd949498ce4cc86ca854173'

uuid4() uses os.urandom() which is best random you can get in python.

Nonce should be used only once and hard to predict. Note that uuid4() is harder to predict than uuid1() whereas later is more globally unique. So you can achieve even more strength by combining them:

uuid.uuid4().hex + uuid.uuid1().hex
# 'a6d68f4d81ec440fb3d5ef6416079305f7a44a0c9e9011e684e2c42c0319303d'