最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[整理]Python中的uuid.uuid4()

Python crifan 4669浏览 0评论

折腾:

[已解决]SQLAlchemy中给列的id从数字变成UUID

期间,需要去了解,uuid4是啥。

搜:

uuid.uuid4

21.20. uuid — UUID objects according to RFC 4122 — Python 3.5.2 documentation

Python使用UUID库生成唯一ID – dkcndk – 博客园

Python中生成唯一码(uuid的使用) – Hello World! – 博客频道 – CSDN.NET

Python中产生UUID函数uuid1与uuid4的选择 – 软件开发程序员博客文章收藏网

http://www.programgo.com/article/68512035953/

-》还是用uuid4

因为uuid1,还是基于Mac地址算出来的

-》此处uuid和mac无关,所以不用uuid1

-》uuid4,足够随机,够用了。

[后记]

from sqlalchemy.sql import func
import uuid
def generateUUID(prefx = “”):
    newUuidHex = uuid.uuid4().hex
    newUuid = prefx + newUuidHex
    gLog.debug(“prefx=%s, newUuidHex=%s, newUuid=%s”, prefx, newUuidHex, newUuid)
    return newUuid
class Event(db.Model):
    __tablename__ = “events”
    id = db.Column(db.String(64), primary_key=True, default = generateUUID(“event-“), nullable=False)

输出:

DEBUG in models [/usr/share/nginx/html/SIPEvents/sipevents/models.py:97]:
prefx=event-, newUuidHex=4f20551a6644474489ab6e0165f0986d, newUuid=event-4f20551a6644474489ab6e0165f0986d
added newEvent=<Event:id=event-4f20551a6644474489ab6e0165f0986d,title=u’\u8ba8\u8bba\u65e5\u5386\u7684\u516c\u4f17\u53f7\u540d\u5b57′,user_openid=oswjmv4X0cCXcfkIwjoDfCkeTVVY>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in db_create [db_create.py:164]:
currentEvents=[<Event:id=event-4f20551a6644474489ab6e0165f0986d,title=u’\u8ba8\u8bba\u65e5\u5386\u7684\u516c\u4f17\u53f7\u540d\u5b57′,user_openid=oswjmv4X0cCXcfkIwjoDfCkeTVVY>], currentEventsCount=1

20.15. uuid — UUID objects according to RFC 4122 — Python 2.7.12 documentation

然后用代码:

def generateUUID(prefx = “”):
    # newUuidHex = uuid.uuid4().hex
    # newUuid = prefx + newUuidHex
    # gLog.debug(“prefx=%s, newUuidHex=%s, newUuid=%s”, prefx, newUuidHex, newUuid)
    generatedUuid4 = uuid.uuid4()
    gLog.debug(“type(generatedUuid4)=%s, generatedUuid4=%s”, type(generatedUuid4), generatedUuid4)
    generatedUuid4Str = str(generatedUuid4)
    newUuid = prefx + generatedUuid4Str
    gLog.debug(“prefx=%s, generatedUuid4Str=%s, newUuid=%s”, prefx, generatedUuid4Str, newUuid)
    return newUuid

输出:

type(generatedUuid4)=<class ‘uuid.UUID’>, generatedUuid4=1ff3408d-3b3f-4872-b833-aaed4a8cc447

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in models [/usr/share/nginx/html/SIPEvents/sipevents/models.py:102]:
prefx=event-, generatedUuid4Str=1ff3408d-3b3f-4872-b833-aaed4a8cc447, newUuid=event-1ff3408d-3b3f-4872-b833-aaed4a8cc447

[总结]

  • uuid.uuid4().hex输出纯字母和数据,中间不带短横线:
    • 4f20551a6644474489ab6e0165f0986d
  • str(uuid.uuid4())输出的是中间带短横线的:
    • 1ff3408d-3b3f-4872-b833-aaed4a8cc447

转载请注明:在路上 » [整理]Python中的uuid.uuid4()

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
52 queries in 0.124 seconds, using 18.78MB memory