Skip to content

Instantly share code, notes, and snippets.

@jace jace/
Created Sep 7, 2010

What would you like to do?
#!/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
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..."
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__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.