Python 如何生成uuid

news/2024/10/19 6:21:48/

UUID

Universally Unique Identifier (UUID),即通用唯一识别码,是一种软件建构的标准。它的目的在于让分布式系统中的所有元素,都能有唯一的辨识信息,而不需要中央控制端做辨识信息的制定。每个人都可以创建与其他人不冲突(重复)的UUID,因此常用作对某一东西的唯一标识。

UUID常用作数据库的主键。

UUID常用作一次计算任务的唯一标识。

Python uuid

Python中内置了一个名为uuid包来处理UUID的生成,使用起来非常方便,它提供了生成36位uuid的方法(32位加上4个’-'号作为间隔符,如果不需要间隔符可以手动去掉)。

Python的uuid包一共提供了4中生成UUID的方法:

  • uuid1()
  • uuid3()
  • uuid4()
  • uuid5()

注:没有uuid2。

使用示例:

import uuidprint(uuid.uuid1())
print(uuid.uuid3(uuid.NAMESPACE_DNS, "test"))
print(uuid.uuid4()) # b983907d-ab25-4002-9dad-c37968936ba8
print(uuid.uuid5(uuid.NAMESPACE_DNS, "test"))

为了信息安全,uuid4之外的结果没有贴出来,读者可以本地自行试试。

注意:生成的uuid不是字符串类型,如果以字符串形式落库或者传递需要手动转换一下:

import uuidprint(type(uuid.uuid4()))
print(str(uuid.uuid4()))

在这里插入图片描述

四种生成uuid方法间的区别

官方文档见:https://docs.python.org/3/library/uuid.html?highlight=uuid#module-uuid

  • uuid1根据当前时间的时间戳加上电脑的mac地址生成,最后12位字符对应mac地址。因为是mac地址,所以本身具备唯一性。但是用这种方法生成uuid并分享泄露了自己的mac地址,因此不推荐使用。
  • uuid3根据传入的namespace和一个由调用者指定字符串调用MD5算法生成。
  • uuid4则是根据随机数生成的,因为不需要参数所以使用起来很方便,但需要注意的是,因为是随机数,所以极其小的概率下也可能会重复。
  • uuid5同样根据传入的namespace和一个由调用者指定字符串生成uuid,如uuid3不同的是,它使用SHA1算法。

源码列在下面👇🏻:

def uuid1(node=None, clock_seq=None):"""Generate a UUID from a host ID, sequence number, and the current time.If 'node' is not given, getnode() is used to obtain the hardwareaddress.  If 'clock_seq' is given, it is used as the sequence number;otherwise a random 14-bit sequence number is chosen."""# When the system provides a version-1 UUID generator, use it (but don't# use UuidCreate here because its UUIDs don't conform to RFC 4122)._load_system_functions()if _generate_time_safe is not None and node is clock_seq is None:uuid_time, safely_generated = _generate_time_safe()try:is_safe = SafeUUID(safely_generated)except ValueError:is_safe = SafeUUID.unknownreturn UUID(bytes=uuid_time, is_safe=is_safe)global _last_timestampimport timenanoseconds = int(time.time() * 1e9)# 0x01b21dd213814000 is the number of 100-ns intervals between the# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.timestamp = int(nanoseconds/100) + 0x01b21dd213814000if _last_timestamp is not None and timestamp <= _last_timestamp:timestamp = _last_timestamp + 1_last_timestamp = timestampif clock_seq is None:import randomclock_seq = random.getrandbits(14) # instead of stable storagetime_low = timestamp & 0xfffffffftime_mid = (timestamp >> 32) & 0xfffftime_hi_version = (timestamp >> 48) & 0x0fffclock_seq_low = clock_seq & 0xffclock_seq_hi_variant = (clock_seq >> 8) & 0x3fif node is None:node = getnode()return UUID(fields=(time_low, time_mid, time_hi_version,clock_seq_hi_variant, clock_seq_low, node), version=1)def uuid3(namespace, name):"""Generate a UUID from the MD5 hash of a namespace UUID and a name."""from hashlib import md5hash = md5(namespace.bytes + bytes(name, "utf-8")).digest()return UUID(bytes=hash[:16], version=3)def uuid4():"""Generate a random UUID."""return UUID(bytes=os.urandom(16), version=4)def uuid5(namespace, name):"""Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""from hashlib import sha1hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()return UUID(bytes=hash[:16], version=5)# The following standard UUIDs are for use with uuid3() or uuid5().NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')
def uuid1(node=None, clock_seq=None):"""Generate a UUID from a host ID, sequence number, and the current time.If 'node' is not given, getnode() is used to obtain the hardwareaddress.  If 'clock_seq' is given, it is used as the sequence number;otherwise a random 14-bit sequence number is chosen."""# When the system provides a version-1 UUID generator, use it (but don't# use UuidCreate here because its UUIDs don't conform to RFC 4122)._load_system_functions()if _generate_time_safe is not None and node is clock_seq is None:uuid_time, safely_generated = _generate_time_safe()try:is_safe = SafeUUID(safely_generated)except ValueError:is_safe = SafeUUID.unknownreturn UUID(bytes=uuid_time, is_safe=is_safe)global _last_timestampimport timenanoseconds = int(time.time() * 1e9)# 0x01b21dd213814000 is the number of 100-ns intervals between the# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.timestamp = int(nanoseconds/100) + 0x01b21dd213814000if _last_timestamp is not None and timestamp <= _last_timestamp:timestamp = _last_timestamp + 1_last_timestamp = timestampif clock_seq is None:import randomclock_seq = random.getrandbits(14) # instead of stable storagetime_low = timestamp & 0xfffffffftime_mid = (timestamp >> 32) & 0xfffftime_hi_version = (timestamp >> 48) & 0x0fffclock_seq_low = clock_seq & 0xffclock_seq_hi_variant = (clock_seq >> 8) & 0x3fif node is None:node = getnode()return UUID(fields=(time_low, time_mid, time_hi_version,clock_seq_hi_variant, clock_seq_low, node), version=1)def uuid3(namespace, name):"""Generate a UUID from the MD5 hash of a namespace UUID and a name."""from hashlib import md5hash = md5(namespace.bytes + bytes(name, "utf-8")).digest()return UUID(bytes=hash[:16], version=3)def uuid4():"""Generate a random UUID."""return UUID(bytes=os.urandom(16), version=4)def uuid5(namespace, name):"""Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""from hashlib import sha1hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()return UUID(bytes=hash[:16], version=5)# The following standard UUIDs are for use with uuid3() or uuid5().NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')

http://www.ppmy.cn/news/187286.html

相关文章

Dell R730服务器inter 500系列网卡与光模块不兼容**

** Dell R730服务器inter 500系列网卡与光模块不兼容** ** 背景* 在业务服务器现场。预装操作系统&#xff0c;刚将Centos7原版镜像安装到服务器时&#xff0c;服务器网卡配置是4个千兆2个万兆&#xff08;Intel X500系列万兆网卡&#xff09;。 现象 服务器预装时无法识别网…

Certificate 超详细解析cer证书(序列号,颁发者,公钥等)

我们一般说的证书就是数字证书&#xff1a;数字证书是指在互联网通讯中标志通讯各方身份信息的一个数字认证&#xff0c;人们可以在网上用它来识别对方的身份 一般有两种&#xff1a;PFX证书、CER证书 PFX证书&#xff1a; 由Public Key Cryptography Standards #12&#xff…

近3万个斗图头像图片大全ACCESS\EXCEL

再发一个头像图片的数据图片包&#xff0c;和《4万多论坛头像个性头像ACCESS数据库》不同的是&#xff0c;这个数据表有一条记录只包含一张图片的&#xff0c;也有一条记录包含多张图片的&#xff0c;具体看截图&#xff0c;截图包含所有字段&#xff1a; 二级目录汇总统计&…

Linux命令详解(14)useradd命令

useradd用于添加一个linux账户。adduser跟本命令等价。 useradd同样属于不复杂但很重要的命令。 --help获得帮助信息。 -b选项&#xff0c;制定家目录的根 -c选项&#xff0c;给新用户添加说明信息 -d选项&#xff0c;给新用户设置家目录 -D选项&#xff0c;新用户使用默认…

PostgresSQL - 生成uuid

一、创建函数 uuid-ossp CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; uuid-ossp模块提供使用多种标准算法之一生成普遍唯一标识符 &#xff08;UUID&#xff09; 的功能。也有功能来产生某些特殊的UUID常数。 此模块依赖于 OSSP UUID 库&#xff0c;该库可在 http:…

创想ender3-V2切片软件参考设置,来优化DIY的3d打印机

创想ender3作为这几年的热门明星打印机&#xff0c;近来终于入手了&#xff0c;可以用他们切片软件的参数设置&#xff0c;优化自己diy的打印机。 1.Start G-code预备打印前划线先挤出材料&#xff0c;ender3打印前先在一边画200mm的线&#xff0c;让挤出机充分挤出线材 它的…

delphi fmx android 屏幕分辨率

android下,和windows系统获取分辨率,有一定的区别 比如我手机是2460x1080像素 但我在android下用screen.width,screen.height得到的是692*300 多 刚开始没在意,因为开发的app一切正常 后来到客户电视上,客户看到自己电视 是900多x500多,说分辨率有问题 于是我开始找an…

Java 生成X.509 V3证书

使用Java语言生成X.509 V3证书 1. X.509 V3证书 X.509 是公钥证书的格式标准, 广泛用于 TLS/SSL 安全通信或者其他需要认证的环境中。 X.509 证书可以由 CA&#xff08;Certificate Authority&#xff0c;数字证书认证机构&#xff09;颁发&#xff0c;也可以自签名产生。 X…