Skip to content

Instantly share code, notes, and snippets.

@jace
Created September 7, 2010 06:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jace/567961 to your computer and use it in GitHub Desktop.
Save jace/567961 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Functions to represent UUIDs as Base64 strings.
Base64 typically uses '+' and '/' as encoding characters. Neither are URL-safe,
so these functions use ',' and '-'. The characters '.' and '_' were considered,
but rejected, as some web frameworks will treat any URL fragment starting with
them as a hidden resource.
"""
import uuid
import base64
ALTCHARS=',-'
def uuid_to_ascii(u=None):
"""
Convert or create a UUID and return as a Base64 string.
"""
if u is None:
u = uuid.uuid4()
return base64.b64encode(u.bytes, altchars=ALTCHARS).replace('=', '')
def ascii_to_uuid(ascii):
"""
Convert an ASCII string back into a UUID. The string must
have been created by :func:`uuid_to_ascii`.
"""
ascii = ascii + '=' * (len(ascii) % 4)
return uuid.UUID(bytes=base64.b64decode(ascii, altchars=ALTCHARS))
def _test():
print "Testing with a hundred random UUIDs..."
print
for x in range(100):
u1 = uuid.uuid4()
a = uuid_to_ascii(u1)
u2 = ascii_to_uuid(a)
print "UUID: %s, ASCII: %s" % (str(u1), a)
assert u1 == u2
if __name__ == '__main__':
_test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment