Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## User Model
- ```python
- class User(UserMixin, db.Model):
- id = db.Column(db.Integer, primary_key=True)
- username = db.Column(db.String(64), index=True, unique=True, nullable=False)
- uuid = db.Column(db.String(64), index=True, default=uuid4().__str__, unique=True)
- email = db.Column(db.String(120), index=True, unique=True)
- password_hash = db.Column(db.String(128), nullable=False)
- ```
- ### Issue Description
- The server keeps generating this same UUID, which, when using uuid4 should be next to impossible. The uuid value takes the default, which in python, must be a callable, i.e. type=function, so I was passing it
- ```python
- default=uuid4().__str__
- ```
- so it would convert the UUID object to string before persisting to the db. I didn't notice the bug, but the issue is that I wanted a new uuid to be created each time a user is created, but instead a new string
- ```python
- __str__
- ```
- was being created with the same uuid values.
- ### Solution
- The solution is to wrap the uuid call in a lambda, so we can both generate a unique uuid, and call tostring() on it.
- ```python
- default=lambda: uuid4().__str__()
- ```
- Wrapping with ```lambda``` enables uniquely call ```uuid4()``` and tostring(), and make it callable.
- ### Final Result
- ```python
- class User(UserMixin, db.Model):
- id = db.Column(db.Integer, primary_key=True)
- username = db.Column(db.String(64), index=True, unique=True, nullable=False)
- uuid = db.Column(db.String(64), index=True, default=lambda: uuid4().__str__(), unique=True)
- email = db.Column(db.String(120), index=True, unique=True)
- password_hash = db.Column(db.String(128), nullable=False)
- ```
- keywords=Flask, SQLAlchemy, uuid, error, collision, uuid4, uuid collision
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement