1

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

3
  • How about set a field with unique constraint? Commented Apr 2, 2017 at 14:59
  • use uuid library Commented Apr 2, 2017 at 15:07
  • got it, I am using uuid and base64 to generate friendly unique url. Thanks! Commented Apr 2, 2017 at 15:22

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

4 Comments

But are you still seting the primary_key proprery to True in the UserModel declaration?
yes, since primary_key should be unique, UUID can handle that.
If you use sqlalchemy_utils dedicated type UUIDType, you can declare the primary key like this: uuid = Column(UUIDType, primary_key=True)
sqlalchemy_utils works, but if you are using Flask-Migrate, it doesn't generate the migration version properly. I had to change manually the parameters passed to the UUIDType.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.