liveBook · Manning

Universally unique identifier

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

A universally unique identifier (UUID) is a standardized 128-bit identifier conventionally represented as a hexadecimal string and intended to be globally unique.

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

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Explains UUID primary keys through a generator and table-merge scenario, but does not detail identifier internals.
Examples
Illustrates a generated User key, conflicting integer IDs during a table merge, and integer-versus-UUID order URLs.
What it assumes
Assumes familiarity with Python models and database keys while supplying the short UUID-generation function.
What you can do after
Apply it via Python’s `uuid4()` and SQLAlchemy to assign UUID primary keys to user records.
How it connects
Connects UUIDs to primary keys, foreign keys, relational databases, HTTP session cookies, and authentication.

Also explained in

Compare how 10 books explain universally unique identifier →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.