Search code examples
pythonflasksqlalchemyflask-sqlalchemy

ID generator with python for sqlachamy in API


Generating 6-Digit ID Numbers for Items in Flask-SQLAlchemy

I'm currently working on a Flask-SQLAlchemy project and need some guidance on generating unique 6-digit ID numbers for items.

I'm considering two approaches and would appreciate advice on which one is better:

Approach 1: UUID Generator

import uuid

def generate_id():
    return str(uuid.uuid4())[:6]

And then using it in my model:

class Item(db.Model):
    id = db.Column(db.String(6), primary_key=True, default=generate_id, unique=True)
    # Other item attributes

OR

Approach 2: String Attribute

class Item(db.Model):
    id = db.Column(db.String(6), primary_key=True, unique=True)
    # Other item attributes

I want to ensure the generated IDs are unique, and I'm looking for the most efficient and best practice approach. Any insights or alternative methods would be greatly appreciated!

my whole code:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    last_name = db.Column(db.String(50), nullable=False)
    birthdate = db.Column(db.DateTime, nullable=False)
    phone = db.Column(db.String(15), nullable=False)
    e_mail = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(256), nullable=False)
    city = db.Column(db.String(50), nullable=False)
    street = db.Column(db.String(50), nullable=False)

    def __init__(self, name, last_name, birthdate, phone, e_mail, password, city, street):
        self.name = name
        self.last_name = last_name
        self.birthdate = birthdate
        self.phone = phone
        self.e_mail = e_mail
        self.password = password
        self.city = city
        self.street = street

Solution

  • If you want your IDs to be unique, setting the 'unique' flag to true is definetly a good idea.
    If I understood correctly, your problem is that you don't really know how to generate the ID.

    I recommand you this article on how to generate 'random' strings : https://pynative.com/python-generate-random-string/

    Here is a bit of code out of the article that matches your requirements :

    import secrets
    import string
    
    # secure random string
    secure_str = ''.join((secrets.choice(string.ascii_letters) for i in range(6)))
    print(secure_str)
    # Output QQkABL
    

    Note : There are chances that you will get errors (there will always be), because there is a finite number of combinations of 6 letters. With the code I gave you there are 19,770,609,664. You have a 50% chance of getting a collision after 165,553 generations !