简体   繁体   中英

How to generate low character primary keys for NoSQL/DynamoDB?

I need to generate room codes for a Flask project, in a similar style to how https://jackbox.tv/ does it.

These room codes will serve as the primary key in a DynamoDB table, and as such will need to be unique.

One option is to use UUIDs, however these are very large and are not user-friendly to type in. Is there a way to generate short (~4-8 character), unique-ish codes without repeatedly querying the DB?

You can use base36 representation of current timestamp which will be 8 characters long and probability of repeated will be very low. in practice this works good.

import base36
from datetime import datetime

key = base36.dumps(int(datetime.utcnow().timestamp() * 1000))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM