Advertisement
Guest User

ogcio.vu

a guest
Aug 9th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """Database module, including the SQLAlchemy database object and DB-related utilities."""
  3. from sqlalchemy.orm import relationship
  4.  
  5. from app import db
  6.  
  7. # Alias common SQLAlchemy names
  8. Column = db.Column
  9. relationship = relationship
  10.  
  11.  
  12. class CRUDMixin(object):
  13. """Mixin that adds convenience methods for CRUD (create, read, update, delete) operations."""
  14.  
  15. @classmethod
  16. def create(cls, **kwargs):
  17. """Create a new record and save it the database."""
  18. instance = cls(**kwargs)
  19. return instance.save()
  20.  
  21. def update(self, commit=True, **kwargs):
  22. """Update specific fields of a record."""
  23. for attr, value in kwargs.items():
  24. setattr(self, attr, value)
  25. return commit and self.save() or self
  26.  
  27. def save(self, commit=True):
  28. """Save the record."""
  29. db.session.add(self)
  30. if commit:
  31. db.session.commit()
  32. return self
  33.  
  34. def delete(self, commit=True):
  35. """Remove the record from the database."""
  36. db.session.delete(self)
  37. return commit and db.session.commit()
  38.  
  39.  
  40. class Model(CRUDMixin, db.Model):
  41. """Base model class that includes CRUD convenience methods."""
  42.  
  43. __abstract__ = True
  44.  
  45.  
  46. # From Mike Bayer's "Building the app" talk
  47. # https://speakerdeck.com/zzzeek/building-the-app
  48. class SurrogatePK(object):
  49. """A mixin that adds a surrogate integer 'primary key' column named ``id`` to any declarative-mapped class."""
  50.  
  51. __table_args__ = {'extend_existing': True}
  52.  
  53. id = db.Column(db.Integer, primary_key=True)
  54.  
  55. @classmethod
  56. def get_by_id(cls, record_id):
  57. """Get record by ID."""
  58. if any(
  59. (isinstance(record_id, basestring) and record_id.isdigit(),
  60. isinstance(record_id, (int, float))),
  61. ):
  62. return cls.query.get(int(record_id))
  63. return None
  64.  
  65.  
  66. def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
  67. """Column that adds primary key foreign key reference.
  68.  
  69. Usage: ::
  70.  
  71. category_id = reference_col('category')
  72. category = relationship('Category', backref='categories')
  73. """
  74. return db.Column(
  75. db.ForeignKey('{0}.{1}'.format(tablename, pk_name)),
  76. nullable=nullable, **kwargs)
  77.  
  78.  
  79. class User(Model, SurrogatePK):
  80. __tablename__ = 'user'
  81.  
  82. username = Column(db.Unicode(50), nullable=False, unique=True)
  83. password = Column(db.Unicode(50), nullable=False)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement