Python Time-Ordered UUID
โฑ๏ธ

Python Time-Ordered UUID

Tags
Dev
Published
Published August 4, 2022

Why?

notion image
UUID1์€ ์‹œ๊ฐ„์„ ์ฃผ๊ธด ํ•˜์ง€๋งŒ, ์‹คํ–‰ํ•˜๋Š” ์žฅ๋น„์˜ mac ์ฃผ์†Œ๊ฐ€ ๋…ธ์ถœ๋œ๋‹ค๋Š” ์  & Multiprocessing ์‚ฌ์šฉ์‹œ UUID ์ˆœ์„œ๊ฐ€ ์‹ค์ œ time ์ˆœ์„œ์™€ ๊ฐ™์ง€ ์•Š์„์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์ด ์ด์Šˆ๊ฐ€ ์žˆ๋‹ค.
Ordered UUID๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ random mac ์ฃผ์†Œ ๊ธฐ๋ฐ˜์˜ UUID1์„ ์‚ฌ์šฉํ•˜๊ณ , ๋‚˜์˜ค๋Š” ํ˜•์‹์€ UUID4 ํ˜•์‹์œผ๋กœ ๋‚˜์™€ Django์˜ UUID Field์™€ ๊ถํ•ฉ์ด ๋งž๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
ํŠนํžˆ, ์ด๋ ‡๊ฒŒ Time-๊ธฐ๋ฐ˜ Ordered UUID๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ์—, Primary Key๋กœ ํ•ด๋‹น Column์„ ์‚ฌ์šฉํ•ด์ฃผ๋ฉด ๋ณ„๋‹ค๋ฅธ 1,2,3..์™€ ๊ฐ™์€ ordered pk ์—†์ด๋„ ์‹œ๊ฐ„์ˆœ์œผ๋กœ ์ •๋ ฌ์ด ๊ฐ€๋Šฅํ•˜๋‹ค๋Š” ์ ์—์„œ ์˜๋ฏธ๊ฐ€ ์žˆ๋‹ค.
ย 
๋‹ค๋งŒ, ์ด๋Ÿฌํ•œ Time based UUID๋Š” ์‹œ๊ฐ„์ด ๊ฒน์น˜๋Š” ๋ถ€๋ถ„์—์„œ ๊ณตํ†ต์ธ ๋ถ€๋ถ„์ด ์žˆ์–ด์„œ, API Key๋“ฑ์œผ๋กœ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋œ๋‹ค.
ย 

OrderedUUID

์„ค์น˜

pip install ordereduuid

์‚ฌ์šฉ

from ordereduuid import OrderedUUID uuid = OrderedUUID()
from ordereduuid import OrderedUUID uid = OrderedUUID() uid = "-".join(str(uid).split("-")[:2]) print(f"{uid=}") # ์‹œ๊ฐ„๋ถ€๋ถ„+UID์ผ๋ถ€

Django ์—์„œ์˜ ์‚ฌ์šฉ

from django.db import models from ordereduuid import OrderedUUID class Subscriber(models.Model): uid = models.UUIDField( primary_key=True, default=OrderedUUID, editable=False )
ย 

TimeFlake

timeflake
anthonynsimon โ€ข Updated Sep 15, 2022

์„ค์น˜

pip install timeflake

์‚ฌ์šฉ

import timeflake # Create a random Timeflake flake = timeflake.random() >>> Timeflake(base62='00mx79Rjxvfgr8qat2CeQDs') # Get the base62, int, hex or bytes representation flake.base62 >>> '00mx79Rjxvfgr8qat2CeQDs' flake.hex >>> '016fa936bff0997a0a3c428548fee8c9' flake.int >>> 1909005012028578488143182045514754249 flake.bytes >>> b'\x01o\xa96\xbf\xf0\x99z\n<B\x85H\xfe\xe8\xc9' # Convert to the standard library's UUID type flake.uuid >>> UUID('016fa936-bff0-997a-0a3c-428548fee8c9')

Django์—์„œ์˜ ์‚ฌ์šฉ

from timeflake.extensions.django import TimeflakePrimaryKeyBinary class Item(models.Model): item_id = TimeflakePrimaryKeyBinary() # ...
ย