zoukankan      html  css  js  c++  java
  • shortuuid:短的uuid

    楔子

    我们以前想生成随机字符串的时候,会使用uuid,比如:

    import uuid
    print(uuid.uuid4())  # 56981b16-0dde-477e-9f07-e46a76d01d2c
    

    但是这个生成的uuid太长了,于是便有了shortuuid。

    用法

    import shortuuid
    print(shortuuid.uuid())  # SkDQBhEjUfygRQgPGTaYch
    

    我们看到此时生成的uuid就短很多了,当然我们也可以生成指定长度的uuid

    import shortuuid
    
    print(shortuuid.ShortUUID().random(5))  # SRD7J
    print(shortuuid.ShortUUID().random(6))  # dLhUFf
    print(shortuuid.ShortUUID().random(10))  # 4rcCPd6Ubm
    

    生成的uuid所使用的字符是:a-z、A-Z、2-9,我们可以自己指定用于生成uuid的字符。

    import shortuuid
    
    # 输出用于生成uuid的字符
    print(shortuuid.get_alphabet())  # 23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz
    # 设置
    shortuuid.set_alphabet("abcdefg")
    print(shortuuid.uuid())  # dadgfgegadfdcdfbccffgfgfegbgcdgabfebcfdecccgfb
    # 我们看到输出变长了,这是因为用于生成的字符变少了。为了安全,内容就变多了
    
    print(shortuuid.get_alphabet())  # abcdefg
    
    
    # 但是对于这种方式生成uuid没有影响
    print(shortuuid.ShortUUID().random(5))  # GKmm6
    # 当然我们也可以重新指定
    print(shortuuid.ShortUUID(alphabet="abcdefg").random(5))  # edddf
    

    另外shortuuid还可以uuid模块搭配使用

    import shortuuid
    import uuid
    
    u = uuid.uuid4()
    s = shortuuid.encode(u)
    print(u)  # cf502b50-f75d-4f36-94a9-6bd04789ca55
    print(s)  # etUe7amvdJvHQY6Emf2TiL
    print(shortuuid.decode(s) == u)  # True
    
  • 相关阅读:
    软件工程期末考试复习(五)
    软件工程期末考试复习(四)
    软件工程期末考试复习(三)
    软件工程期末考试复习(二)
    shell脚本与mongo交互
    python使用单例模式创建MySQL链接
    python with上下文的浅谈
    Docker 基础概念科普 和 常用操作介绍
    MySQL聚集索引和非聚集索引
    为什么选择Python
  • 原文地址:https://www.cnblogs.com/traditional/p/12555261.html
Copyright © 2011-2022 走看看