Aaron
Aaron

Reputation: 2351

Python key generation strategy for URLs

I have a database of entities that I want to display in a web ui. I want a short, alphanumeric string that I can generate from the entity's key. I came to the conclusion that base32 was a good solution (particularly because I wanted the keys to be case-insensitive so they could be read verbally, etc). Is there anything shorter or more space efficient than the below?

import base64
def b32urlencode(x):
    return base64.b32encode(x).strip('=').lower()

def b32urldecode(x):
    return base64.b32decode(x + ('=' * (8 - (len(x) % 8))))

Upvotes: 1

Views: 141

Answers (1)

Chris Johnson
Chris Johnson

Reputation: 21996

The answer depends on how human-readable and -typeable you want the URL to be.

Base64 uses upper- and lower-case letters plus -, +, _, / and =. Upper and lower case may or may not be distinguishable by your web server or application, depending on how you've configured them. If you expect your users to be able type URLs (not just click on them) then upper and lower case alphabetics can be a problem even if the server & app tolerate them.

Depending on the above, consider base 62 (a-z, A-Z and 0-9) or 36 (a-z case insensitive and 0-9).

Upvotes: 1

Related Questions