class User(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(120), unique=True) def __init__(self, email): self.email = email def __repr__(self): return '<User %r>' % self.email
class User(db.Model): email = db.Column(db.String(255), primary_key=True) username = db.Column(db.String(255)) upassword = db.Column(db.String(255)) uauthority = db.Column(db.Integer) def __init__(self, username, password, email, authority): self.email = email self.username = username self.upassword = password self.uauthority = authority
class UserConnection(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey(User.id)) user = db.relationship(User) backend = db.Column(db.String) external_id = db.Column(db.String) data = db.Column(db.Text) def __repr__(self): return "<UserConnection %r:%r:%r>" % (self.user_id, self.backend, self.external_id)
class User(db.Model): __tablename__ = "users" id = db.Column(UUID(as_uuid=True), default=uuid.uuid4, unique=True, primary_key=True) email = db.Column(db.String(128), unique=True, nullable=False) name = db.Column(db.String(128), nullable=False) surname = db.Column(db.String(128), nullable=False) role = db.Column(db.String(128), nullable=False) phone = db.Column(db.String(128)) city = db.Column(db.String(128)) type = db.Column(db.String(50), nullable=False) blocked = db.Column(db.Boolean(), default=False, nullable=False) __mapper_args__ = { 'polymorphic_on': type, 'polymorphic_identity': 'users' } def __init__(self, **kwargs): self.assert_key(kwargs, 'name') self.assert_key(kwargs, 'surname') self.assert_key(kwargs, 'email') if kwargs.get('role', '') not in ROLES: raise ValueError('Invalid user role') if not re.match(re.compile(r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"), kwargs['email']): raise ValueError('Invalid email') self.email = kwargs['email'] self.name = kwargs['name'] self.surname = kwargs['surname'] self.role = kwargs['role'] self.phone = kwargs.get('phone', None) self.city = kwargs.get('city', None) def assert_key(self, values_dict, key): if not values_dict.get(key, ''): raise ValueError('Missing user %s' % key) def serialize(self): return { "id": str(self.id), "email": self.email, "name": self.name, "surname": self.surname, "role": self.role, "phone": self.phone, "city": self.city, "blocked": self.blocked } def password_matches(self, password): raise NotImplementedError() def update(self, values): for key,value in values.items(): setattr(self, key, value)
class Personnel(db.Model): perid = db.Column(db.String(255), primary_key=True) pername = db.Column(db.String(255)) perdegree = db.Column(db.String(255)) pereb = db.Column(db.String(255)) pertitle = db.Column(db.String(255)) def __init__(self, perid, pername, perdegree, pereb, pertitle): self.perid = perid self.pername = pername self.perdegree = perdegree self.pereb = pereb self.pertitle = pertitle
class Monograph(db.Model): moissn = db.Column(db.String(255), primary_key=True) moname = db.Column(db.String(255)) moauthor = db.Column(db.String(255)) mopress = db.Column(db.String(255)) modp = db.Column(db.String(255)) def __init__(self, moissn, moname, moauthor, mopress, modp): self.moissn = moissn self.moname = moname self.moauthor = moauthor self.mopress = mopress self.modp = modp
class List(Model): """ Base Model Provides: pk (primary key) created_at (creation date) """ name = db.Column(db.String(), nullable=False) items = db.relationship('Item', backref='items', lazy=True) def __repr__(self): return f'<List {self.id} name: {self.name}>' @property def dictionary(self): return { 'pk': self.pk, 'created_at': self.created_at, 'name': self.name, 'items': [ item.dictionary for item in Item.query.filter(Item.list_id == self.pk) ] }
class Server(db.Model): __tablename__ = "servers" id = db.Column(UUID(as_uuid=True), default=uuid.uuid4, unique=True, primary_key=True) nombre = db.Column(db.String(256), nullable=False) token = db.Column(db.String(256), nullable=False) def __init__(self, **kwargs): self.assert_key(kwargs, 'nombre') self.assert_key(kwargs, 'token') self.nombre = kwargs['nombre'] self.token = kwargs['token'] def assert_key(self, values_dict, key): if not values_dict.get(key, ''): raise ValueError('Missing server %s' % key) def serialize(self): return {"id": str(self.id), "nombre": self.nombre, "token": self.token}
class Item(Model): """ Base Model Provides: pk (primary key) created_at (creation date) """ summary = db.Column(db.String(), nullable=False) details = db.Column(db.String(), nullable=False) active = db.Column(db.Boolean, nullable=False, default=False) list_pk = db.Column(db.Integer, db.ForeignKey('list.pk'), nullable=False) def __repr__(self): return f'<Item {self.pk} details: {self.details} summary: {self.summary} active: {self.active} list_pk: {self.list_pk}>' @property def dictionary(self): return { 'pk': self.pk, 'created_at': self.created_at, 'summary': self.summary, 'details': self.details, 'active': self.active, 'list_pk': self.list_pk }
class Paper(db.Model): paperid = db.Column(db.String(255), primary_key=True) papername = db.Column(db.String(255)) paperfa = db.Column(db.String(255)) paperca = db.Column(db.String(255)) paperpt = db.Column(db.String(255)) paperpn = db.Column(db.String(255)) papervp = db.Column(db.String(255)) papersp = db.Column(db.String(255)) paperep = db.Column(db.String(255)) paperct = db.Column(db.String(255)) def __init__(self, paperid, papername, paperfa, paperca, paperpt, paperpn, papervp, papersp, paperep, paperct): self.paperid = paperid self.papername = papername self.paperfa = paperfa self.paperca = paperca self.paperpt = paperpt self.paperpn = paperpn self.papervp = papervp self.papersp = papersp self.paperep = paperep self.paperct = paperct
class Patent(db.Model): paid = db.Column(db.String(255), primary_key=True) paname = db.Column(db.String(255)) paapplicant = db.Column(db.String(255)) pada = db.Column(db.String(255)) patype = db.Column(db.String(255)) paie = db.Column(db.String(255)) paapc = db.Column(db.String(255)) paauc = db.Column(db.String(255)) def __init__(self, paid, paname, paapplicant, pada, patype, paie, paapc, paauc): self.paid = paid self.paname = paname self.paapplicant = paapplicant self.pada = pada self.patype = patype self.paie = paie self.paapc = paapc self.paauc = paauc
class SRTA(db.Model): staid = db.Column(db.String(255), primary_key=True) staname = db.Column(db.String(255)) statype = db.Column(db.String(255)) stawinner = db.Column(db.String(255)) start = db.Column(db.String(255)) statime = db.Column(db.String(255)) stait = db.Column(db.String(255)) stanote = db.Column(db.String(255)) def __init__(self, staid, staname, statype, stawinner, start, statime, stait, stanote): self.staid = staid self.staname = staname self.statype = statype self.stawinner = stawinner self.start = start self.statime = statime self.stait = stait self.stanote = stanote
class Meeting(db.Model): mid = db.Column(db.String(255), primary_key=True) mname = db.Column(db.String(255)) mmember = db.Column(db.String(255)) mtime = db.Column(db.String(255)) maddress = db.Column(db.String(255)) mtype = db.Column(db.String(255)) mnote = db.Column(db.String(255)) def __init__(self, mid, mname, mmember, mtime, maddress, mtype, mnote): self.mid = mid self.mname = mname self.mmember = mmember self.mtime = mtime self.maddress = maddress self.mtype = mtype self.mnote = mnote
class BookBnBUser(User): password = db.Column(db.String(128)) __mapper_args__ = { 'polymorphic_identity': 'bookbnb_user' } def __init__(self, **kwargs): self.assert_key(kwargs, 'password') if len(kwargs['password']) < 8: raise ValueError('Invalid user password: expected length of 8 characters') super().__init__(**kwargs) self.change_password(kwargs['password']) def password_matches(self, password): return check_password_hash(self.password, password) def change_password(self, new_password): hashed_password = generate_password_hash(new_password, method='sha256') self.password = hashed_password
class Model(db.Model, QueryMixin): """Abstract base class for all app models. Provides an `id` & `created_at` column to every model. To define models, follow this example: from .base import Model class MyModel(Model): # model definition """ __abstract__ = True id = db.Column(db.Integer, primary_key=True) @declared_attr def created_at(cls): return db.Column(ArrowType, default=utcnow, nullable=False, index=True) @property def class_name(self): """Shortcut for returning class name.""" return unicode(self.__class__.__name__) @classmethod def __ignore__(cls): """Custom class attr that lets us control which models get ignored. We are using this because knowing whether or not we're actually dealing with an abstract base class is only possible late in the class's init lifecycle. This is used by the dynamic model loader to know if it should ignore. """ return cls.__name__ in ('Model',) # can add more abstract base classes here def __repr__(self): """"Returns a string representation of every object. Useful for logging & error reporting. Example: >>> obj = MyModel() >>> print obj MyModel.123 Can be overridden by subclasses to customize string representation. """ return u"{}.{}".format(self.class_name, self.id) @declared_attr def __tablename__(cls): """Generate a __tablename__ attr for every model that does not have inherited tables. Ensures table names match the model name without needing to declare it. """ if has_inherited_table(cls): return None return cls.__name__.lower() ################################################################################## # I added the base methods below to augment the foundation built up by bob waycott ################################################################################## @property def dictionary(self): return {} @property def __skip_attrs__(self): return [] def update(self, data): caught_id = data.get('id') if caught_id and self.id != caught_id: _id = self.id db.session.close() raise ApiDatabaseError(403, f"Cannot modify primary keys got:({caught_id}) for: {_id}") invalid_keys = list() for key, value in data.items(): if any([key == skip for skip in self.__skip_attrs__]) or not hasattr(self, key): invalid_keys.append(value) if len(invalid_keys) > 0: db.session.close() raise ApiDatabaseError(422, f"Invalid Database Fields: {','.join(invalid_keys)}") else: for key, value in data.items(): try: setattr(self, key, value) except Exception as e: log.exception(e) db.session.close() raise ApiDatabaseError(400, f"Rejected for : {key}") try: returns = self.dictionary self.save() db.session.close() return returns except StatementError as e: db.session.close() raise ApiDatabaseError(400, f'Rejected for: {e.orig}') raise ApiDatabaseError(400, f'Rejected!') @staticmethod def toTimeString(time_stamp): timezone = 'US/Mountain' return str(time_stamp.to(timezone))
class Model(db.Model, QueryMixin): """Abstract base class for all app models. Provides a `pk` & `created_at` column to every model. To define models, follow this example: from .base import Model class MyModel(Model): # model definition """ __abstract__ = True pk = db.Column(db.Integer, primary_key=True) @declared_attr def created_at(cls): return db.Column(ArrowType, default=utcnow, nullable=False, index=True) @property def class_name(self): """Shortcut for returning class name.""" return unicode(self.__class__.__name__) @classmethod def __ignore__(cls): """Custom class attr that lets us control which models get ignored. We are using this because knowing whether or not we're actually dealing with an abstract base class is only possible late in the class's init lifecycle. This is used by the dynamic model loader to know if it should ignore. """ return cls.__name__ in ('Model', ) # can add more abstract base classes here def __repr__(self): """"Returns a string representation of every object. Useful for logging & error reporting. Example: >>> obj = MyModel() >>> print obj MyModel.123 Can be overridden by subclasses to customize string representation. """ return u"{}.{}".format(self.class_name, self.pk) @declared_attr def __tablename__(cls): """Generate a __tablename__ attr for every model that does not have inherited tables. Ensures table names match the model name without needing to declare it. """ if has_inherited_table(cls): return None return cls.__name__.lower()
class Project(db.Model): proid = db.Column(db.String(255), primary_key=True) proname = db.Column(db.String(255)) proyear = db.Column(db.String(255)) procategory = db.Column(db.String(255)) proheader = db.Column(db.String(255)) promember = db.Column(db.String(255)) prost = db.Column(db.String(255)) proet = db.Column(db.String(255)) prouu = db.Column(db.String(255)) propf = db.Column(db.String(255)) progu = db.Column(db.String(255)) def __init__(self, proid, proname, proyear, procategory, proheader, promember, prost, proet, prouu, propf, progu): self.proid = proid self.proname = proname self.proyear = proyear self.procategory = procategory self.proheader = proheader self.promember = promember self.prost = prost self.proet = proet self.prouu = prouu self.propf = propf self.progu = progu
def created_at(cls): return db.Column(ArrowType, default=utcnow, nullable=False, index=True)
class UserProfile(UserMixin, Model): """ .base.Model provides: id (primary key) created_at (creation date) flask_login.UserMixin provides: """ alternate_id = db.Column(db.String(256), nullable=False, unique=True) social_id = db.Column(db.String(256), nullable=True, unique=True) nickname = db.Column(db.String(256), nullable=True) email = db.Column(db.String(256), nullable=True) picture = db.Column(db.String(256), nullable=True) name = db.Column(db.String(256), nullable=True) family_name = db.Column(db.String(256), nullable=True) given_name = db.Column(db.String(256), nullable=True) locale = db.Column(db.String(16), default='en', nullable=False) updated_at = db.Column(ArrowType, default=utcnow, index=True) email_verified = db.Column(db.Boolean, nullable=True, default=False) def __repr__(self): return f'<User {self.id}: email: {self.email} nickname: {self.nickname}>' @property def __skip_attrs__(self): return [ "__repr__", 'records', 'manager', 'patron', 'provider', 'scheduler', 'addresses', 'created_at', 'update' ] @property def dictionary(self): return { 'id': self.id, 'created_at': self.toTimeString(self.created_at), 'alternate_id': self.alternate_id, 'social_id': self.social_id, 'email': self.email, 'email_verified': self.email_verified, 'name': self.name, 'family_name': self.family_name, 'given_name': self.given_name, 'locale': self.locale, 'updated_at': self.toTimeString(self.updated_at), } @property def all_records(self): return [] @property def all_records_serialized(self): return [] @classmethod def get_or_create(cls, sub): existing_user = cls.query.filter(cls.alternate_id == sub).one_or_none() if existing_user: return existing_user else: new_user = cls(alternate_id=sub) new_user.save() this_id = new_user.id db.session.close() initialized_user = cls.get(this_id) return initialized_user