简体   繁体   中英

Using Python's UUID to generate unique IDs, should I still check for duplicates?

I'm using Python's UUID function to create unique IDs for objects to be stored in a database:

>>> import uuid
>>> print uuid.uuid4()
2eec67d5-450a-48d4-a92f-e387530b1b8b

Is it ok to assume that this is indeed a unique ID?

Or should I double-check that this unique ID has not already been generated against my database before accepting it as valid.

You should always have a duplicate check, even though the odds are pretty good, you can always have duplicates.

I would recommend just adding a duplicate key constraint in your database and in case of an error retry.

I would use uuid1 , which has zero chance of collisions since it takes date/time into account when generating the UUID (unless you are generating a great number of UUID's at the same time).

You can actually reverse the UUID1 value to retrieve the original epoch time that was used to generate it.

uuid4 generates a random ID that has a very small chance of colliding with a previously generated value, however since it doesn't use monotonically increasing epoch time as an input (or include it in the output uuid), a value that was previously generated has a (very) small chance of being generated again in the future.

As long as you create all uuids on same system, unless there is a very serious flaw in python implementation (what I really cannot imagine), RFC 4122 states that they will all be distinct (edited : if using version 1,3 or 5).

The only problem that could arise with UUID, were if two systems create UUID exactly at the same moment and :

  • use same MAC address on their network card (really uncommon) and you are using UUID version 1
  • or use same name and you are using UUID version 3 or 5
  • or got same random number and you are using UUID version 4 (*)

So if you have a real MAC address or use an official DNS name or a unique LDAP DN, you can take for true that the generated uuids will be globally unique.

So IMHO, you only have to check unicity if you want to prevent your application against a malicious attack trying to voluntaryly use an existant uuid.

EDIT: As stated by Martin Konecny, in uuid4 the timestamp part is random too and not monotonic. So the possibilily is collision is very limited but not 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM