简体   繁体   English

Django/Python 从 UUID 生成唯一的礼品卡代码

[英]Django/Python generate and unique Gift-card-code from UUID

I'm using Django and into a my model I'm using UUID v4 as primary key.我正在使用 Django 并在我的模型中使用 UUID v4 作为主键。

I'm using this UUID to generate a Qrcode used for a sort of giftcard.我正在使用此 UUID 生成用于某种礼品卡的 Qrcode。

Now the customer requests to have also a giftcard code using 10 characters to have a possibility to acquire the giftcard using the Qrcode (using the current version based on the UUID) as also the possibility to inter manually the giftcard code (to digit 10 just characters).现在,客户还要求使用10 个字符的礼品卡代码,以便有可能使用 Qrcode(使用基于 UUID 的当前版本)获取礼品卡,也可以手动输入礼品卡代码(数字 10 个字符) )。

Now I need to found a way to generate this gift code.现在我需要找到一种方法来生成这个礼物代码。 Obviously this code most be unique.显然这个代码最是独一无二的。

I found this article where the author suggest to use the auto-generaed id (integer id) into the generate code (for example at the end of a random string).我发现这篇文章作者建议在生成代码中使用自动生成的 id(整数 id)(例如在随机字符串的末尾)。 I'm not sure for this because I have only 10 characters: for long id basically I will fire some of available characters just to concatenate this unique section.我不确定这一点,因为我只有 10 个字符:对于 long id,基本上我会触发一些可用的字符来连接这个独特的部分。

For example, if my id is 609234 I will have {random-string with length 4} + 609234 .例如,如果我的 id 是 609234,我将有{random-string with length 4} + 609234

And also, I don't like this solution because I think it's not very sure, It's better to have a completely random code.而且,我不喜欢这个解决方案,因为我认为它不是很确定,最好有一个完全随机的代码。 There is a sort regular-format from malicious user point of view.从恶意用户的角度来看,有一种常规格式。

Do you know a way to generate an unique random string using, for example from an input unique key (in my case the UUIDv4)?您知道一种使用例如输入唯一键(在我的情况下是 UUIDv4)生成唯一随机字符串的方法吗?

Otherwise, do you know some algorithm/approach to generate voucher codes?否则,您知道生成优惠券代码的一些算法/方法吗?

import string
import secrets

unique_digits = string.digits
password = ''.join(secrets.choice(unique_digits) for i in range(6))

print(password)

The above code pallet generates a unique code of integers for the number of digits you want.上面的代码托盘为您想要的位数生成一个唯一的整数代码。 In the above case, it will print a 6-digit unique Integer code.在上述情况下,它将打印一个 6 位唯一整数代码。 If it doesn't let me know, what exactly you want.如果它不让我知道,你到底想要什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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