I’m working with an API that wants me to generate opaque “reference IDs” for transactions with their API, in other words, unique references that users can’t guess or infer in any way. (is ‘infer’ proper english?)
This is what I’ve hacked together currently:
randomRef = randint(0, 99999999999999)
while Transaction.objects.filter(transactionRef = randomRef).count():
randomRef = randint(0, 99999999999999)
Transaction.objects.create(user=user, transactionRef=randomRef, price=999)
unfortunately my database seems to be missing transactions at the moment. I’ve realized that my method isn’t particularly thread safe (say I’m running the same django code on multiple mod_wsgi apache threads, they could all be generating the same randomRef!)
Has anyone got a nicer trick to generate random primary keys for me?
Why not just encrypt the normal sequential ids instead? To someone who doesn’t know the encryption key, the ids will seem just as random. You can write a wrapper that automatically decrypts the ID on the way to the DB, and encrypts it on the way from the DB.