UUID is 128 bits, so you can apply base64 to it directly to get a long string of 22 characters (by removing the fixed padding '==' , as suggested by Gumbo in the comments on the question)
>>> import base64 >>> len(base64.urlsafe_b64encode(uuid.uuid4().bytes).rstrip('=')) 22
Here urlsafe_b64encode and removing '=' are used to avoid characters that do not match the User.username field, including '/' '+' and '='
In addition, the UUID has two fixed bits of '10' (hence the 17th char in hexadecimal representation is always 8,9,A,B ) and four version bits, check the wiki .
So you can throw 4 + 2 = 6 bits into w / 2 effective bits to get a long hexadecimal string 30 characters long:
>>> s = uuid.uuid4().hex >>> len(s[:12] + s[13:16] + s[17:]) 30
That way, you only remove 2 effective bits instead of 8, when you just slice s into s[:30] and you can expect better uniqueness (no more than 1/4 of the coding of the uuid space).
source share