Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. ## User Model
  2.  
  3. ```python
  4. class User(UserMixin, db.Model):
  5. id = db.Column(db.Integer, primary_key=True)
  6. username = db.Column(db.String(64), index=True, unique=True, nullable=False)
  7. uuid = db.Column(db.String(64), index=True, default=uuid4().__str__, unique=True)
  8. email = db.Column(db.String(120), index=True, unique=True)
  9. password_hash = db.Column(db.String(128), nullable=False)
  10. ```
  11.  
  12. ### Issue Description
  13. 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
  14. ```python
  15. default=uuid4().__str__
  16. ```
  17. 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
  18. ```python
  19. __str__
  20. ```
  21. was being created with the same uuid values.
  22.  
  23. ### Solution
  24. The solution is to wrap the uuid call in a lambda, so we can both generate a unique uuid, and call tostring() on it.
  25. ```python
  26. default=lambda: uuid4().__str__()
  27. ```
  28. Wrapping with ```lambda``` enables uniquely call ```uuid4()``` and tostring(), and make it callable.
  29.  
  30.  
  31. ### Final Result
  32.  
  33. ```python
  34. class User(UserMixin, db.Model):
  35. id = db.Column(db.Integer, primary_key=True)
  36. username = db.Column(db.String(64), index=True, unique=True, nullable=False)
  37. uuid = db.Column(db.String(64), index=True, default=lambda: uuid4().__str__(), unique=True)
  38. email = db.Column(db.String(120), index=True, unique=True)
  39. password_hash = db.Column(db.String(128), nullable=False)
  40. ```
  41.  
  42. keywords=Flask, SQLAlchemy, uuid, error, collision, uuid4, uuid collision
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement