A universally unique identifier (UUID) is a way to give a database record an ID intended to remain unique beyond its own table. An auto-incrementing integer works well within one table, but the same integer can appear in another. That difference matters when databases change. section 10.3.2
Consider merging two tables whose primary keys are integers. Duplicate IDs may need to change, which can break foreign keys that refer to the old values. UUID primary keys avoid those conflicts, so existing references can continue to point to the records. section 10.3.2
Generate a user ID
In a Flask application, `get_uuid()` returns `uuid4().hex`. The `User` model uses that function as the default for its string-valued primary key, `user_uid`. The ID identifies the user record and is stored in the HTTP session cookie used during authentication. section 8.2.1
class User(UserMixin, db.Model): #1
__tablename__ = "user" #2
user_uid = db.Column(db.String, primary_key=True, default=get_uuid) #3
first_name = db.Column(db.String, nullable=False) #4
last_name = db.Column(db.String, nullable=False) #4
email = db.Column(db.String, nullable=False, #4
unique=True, index=True) #4
hashed_password = db.Column("password", #4
db.String, nullable=False) #4
active = db.Column(db.Boolean, nullable=False, default=False) #4
created = db.Column(db.DateTime, nullable=False, #5
default=datetime.utcnow) #5
updated = db.Column(db.DateTime, nullable=False, #5
default=datetime.utcnow, onupdate=datetime.utcnow) #5
def get_id(self):
return self.user_uid
@property
def password(self):
raise AttributeError("user password can’t be read")
@password.setter
def password(self, password):
self.hashed_password = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.hashed_password, password)
def __repr__(self):
return f"""
user_uid: {self.user_uid}
name: {self.first_name} {self.last_name}
email: {self.email}
active: {'True' if self.active else 'False'}
"""
The `user_uid` column shows how a SQLAlchemy model assigns the UUID-generating function as its primary-key default. section 8.2.1
UUIDs can also make record IDs in URLs less predictable than sequential integers. Treat that as an incidental obscurity benefit, not the main reason to choose them: their practical value here is keeping record identities stable as tables and relationships change. section 10.3.2









