Python如何缩短uuuid并解码?

标签 python django python-2.7

我正在尝试使用以下方法为我的一个模型创建一个缩短的 ID:

_char_map = string.ascii_letters+string.digits

def index_to_char(sequence):
    return "".join([_char_map[x] for x in sequence])

    def make_short_id(self):
        _id = self.id
        digits = []
        while _id > 0:
            rem = _id % 62
            digits.append(rem)
            _id /= 62
        digits.reverse()
        return index_to_char(digits) 

    @staticmethod
    def decode_id(string):
        i = 0
        for c in string:
            i = i * 64 + _char_map.index(c)
        return i

self.id 是一个 uuid,即 1c7a2bc6-ca2d-47ab-9808-1820241cf4d4,但我收到以下错误:

rem = _id % 62 TypeError: not all arguments converted during string formatting

此方法似乎仅在 idint 时有效。

如何修改缩短uuuid并解码的方法?

更新:

谢谢你的帮助。我试图找到一种方法来创建一个编码和解码方法,该方法采用一个字符串,使其更短然后再次解码。正如所指出的,上述方法永远不能使用字符串 (uuid),

最佳答案

%运算符是字符串格式化或插值运算符,在与字符串一起使用时不返回 Python 中的余数。它将尝试返回一个格式化的字符串。

我不确定你的输入是什么,但尝试使用 int 转换它,这样你就可以获得它的其余部分。

编辑:我现在看到了你的输入,不知道为什么我错过了它。这是将 UUID 转换为数字的一种方法:

import uuid
input = "1c7a2bc6-ca2d-47ab-9808-1820241cf4d4"
id = uuid.UUID(input)
id.int
# returns 37852731992078740357317306657835644116L

不确定“缩短”是什么意思,但看起来您正在尝试对 UUID 进行“base 62 编码”。如果您使用 this question 中的函数你最终会得到以下结果:

uuid62 = base62_encode(id.int)
# uuid62 contains 'RJChvUCPWDvJ7BdQKOw7i'

要取回原始 UUID:

# Create a UUID again
id = uuid.UUID(int=base62_decode(uuid62))

id.hex
# returns '1c7a2bc6ca2d47ab98081820241cf4d4'           

str(id)
# returns '1c7a2bc6-ca2d-47ab-9808-1820241cf4d4'

关于Python如何缩短uuuid并解码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28169164/

相关文章:

python - 计算包含两个较小圆的最小圆的圆心和半径

python - 如何从 SQLAlchemy 查询中获取 AVG?

Python MySQL UTF-8 编码因执行顺序而异

Django不区分大小写的登录,混合大小写的用户名

python - 在虚拟环境中手动安装包并且 pip 要求知道

python - 如何从 NLTK 树中获取标记?

python - 如何从两个列表中找到匹配项?

python - Django Rest - 将字段转换为列表?

django - django_webtest 中的用户身份验证

python-2.7 - 具有OpenCV和Python错误的数据集创建者