os.urandom(20) 生成的随机数会重复吗?
这里的 urandom 应该是调用的系统的随机方法吧
在 Django REST Framework
中 Token 的生成方法
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(Token, self).save(*args, **kwargs)
def generate_key(self):
return binascii.hexlify(os.urandom(20)).decode()
Basically you can think that the probability of conflict is very low, and the length specified here is 20 bits. It cannot be said that there is no conflict at all, but the probability is very low, and basically there will be no conflict.
See documentation
It says The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation.
The data returned is "unpredictable" enough to be used for crypto-related encryption.
I did a test and generated 1000W records. There are no duplicates. You can increase the data test intensity and try again. From a statistical point of view, the probability of this very low-probability event can be considered to be 0.
Of course it will repeat. Since it is a random number, it will repeat randomly.