Reputation: 35
I am building a Rest API using Flask dan Flask-SQLAlchemy. Just wonder, are there any ways to generate a unique ID string primary key? this key will be used for identity API endpoint, like:
POST v0.2/users/4q2VolejRejNmGQB/messages
Instead of
POST v0.2/users/123/messages
I am playing with http://hashids.org/, but seems like had a problem because the primary key will be generated automatically after I save the data while hashids need to generate given integer
Upvotes: 1
Views: 3478
Reputation: 35
I just got the solution. I am using uuid for generating unique primary key and base64 to make it friendly.
import re
import uuid
import base64
def uuid_url64():
rv = base64.b64encode(uuid.uuid4().bytes).decode('utf-8')
return re.sub(r'[\=\+\/]', lambda m: {'+': '-', '/': '_', '=': ''}[m.group(0)], rv)
here is example of the implementation
user1 = UserModel(user_id=str(uuid_url64()), name='rizkiaditya')
Upvotes: 1