Created
July 20, 2020 13:21
-
-
Save iuridiniz/e6a8920e22cc5dcb12edb3f3aa723545 to your computer and use it in GitHub Desktop.
slug generator (from uuid)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from base64 import urlsafe_b64decode, urlsafe_b64encode | |
from uuid import UUID, uuid4 | |
from binascii import Error as BinasciiError | |
def slug(): | |
uuid_ = uuid4() | |
return uuid2slug(uuid_) | |
# https://stackoverflow.com/a/53543324/1522342 | |
def uuid2slug(uuid_): | |
if isinstance(uuid_, str): | |
try: | |
uuid_ = UUID(uuid_) | |
except ValueError: | |
return None | |
return urlsafe_b64encode(uuid_.bytes).decode('utf8').rstrip('=\n') | |
# https://stackoverflow.com/a/53543324/1522342 | |
def slug2uuid(slug): | |
if len(slug) != 22: | |
return None | |
b64 = f'{slug}==' | |
try: | |
bytes = urlsafe_b64decode(b64) | |
except BinasciiError: | |
return None | |
if len(bytes) != 16: | |
return None | |
return UUID(bytes=bytes) | |
if __name__ == '__main__': | |
import sys | |
result = None | |
if len(sys.argv) < 2: | |
result = slug() | |
else: | |
candidate = sys.argv[1] | |
if not result: | |
result = slug2uuid(candidate) | |
if not result: | |
result = uuid2slug(candidate) | |
if not result: | |
sys.exit(1) | |
print(str(result)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment