使用随机主键创建django对象 [英] Creating django objects with a random primary key

查看:352
本文介绍了使用随机主键创建django对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个API,希望我为其API交易生成不透明的参考ID,换句话说,用户无法以任何方式猜测或推断的唯一引用。 (是推断正确的英文?)



这是我目前一直被黑客入侵的:

  randomRef = randint(0,99999999999999)
而Transaction.objects.filter(transactionRef = randomRef).count():
randomRef = randint(0,99999999999999)

Transaction.objects.create(user = user,transactionRef = randomRef,price = 999)

不幸的是,我的数据库似乎目前缺少交易。我已经意识到我的方法不是特别线程安全(比如我在多个mod_wsgi apache线程上运行相同的django代码,他们都可以生成相同的randomRef!)


$ b $有没有人有更好的技巧为我生成随机主键?

解决方案

为什么不加密正常的顺序ids代替?对于不知道加密密钥的人来说,ids将看起来是随机的。您可以编写一个自动解密数据库路径上的ID的包装器,并在DB的路上对其进行加密。


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.

这篇关于使用随机主键创建django对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆