class Recipes(db.Model): """This is Recipes class for table structure.""" __tablename__ = 'recipes' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(40), nullable=False) ingredients = db.Column(db.Text, nullable=False) description = db.Column(db.Text, nullable=False) image_file = db.Column(db.String(20), nullable=False, default='default.jpg') date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) date_updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) category_id = db.Column(db.Integer, db.ForeignKey('categories.id'), nullable=False) category = db.relationship('Categories', foreign_keys=[category_id]) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) user = db.relationship('Users', foreign_keys=[user_id]) def __rerp__(self): """Representation string of an Recipes object.""" return f"Recipes('{self.name}', " \ f"'{self.category_id}', " \ f"'{self.user_id}', " \ f"'{self.date_posted}', " \ f"'{self.date_updated}', " \ f"'{self.image_file}')"
class Application(ModelBase): user_id = db.Column( db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False, ) company_name = db.Column(db.String(255), nullable=False, index=True) application_date = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) application_notes = db.Column(db.Text, nullable=True) position = db.Column(db.String(255), nullable=False, index=True) user = db.relationship( 'User', backref=db.backref('applications', lazy='dynamic'), ) events = db.relationship( 'ApplicationEvent', backref='application', lazy='dynamic', ) contacts = db.relationship( 'ApplicationContact', backref='application', lazy='dynamic', ) keywords = db.relationship('Keyword', secondary=application_keyword, backref=db.backref('applications', lazy='dynamic'), lazy='dynamic')
class Topics(db.Model): id = db.Column(db.Integer, primary_key=True) topic = db.Column(db.String, nullable=False, unique=True) vocabularys = db.relationship('Vocabularys') progress = db.relationship('Progress') # Create function to return String def __repr__(self): return self.id
class WorkType(db.Model): __tablename__ = 'WorkTypes' id = db.Column(db.Integer, name='Id', primary_key=True) guid = db.Column(db.String(255), name='GUID') name = db.Column(db.String(255), name='Name') price_value = db.Column(db.Float, name='PriceValue', nullable=False) salary = db.Column(db.Float, name='Salary', nullable=False) time = db.Column(db.Float, name='Time', nullable=False) order = db.Column(db.Integer, name='Order', nullable=False) description = db.Column(db.Text, name='Description') materials_count = db.Column(db.Text, name='MaterialsCount') formula_id = db.Column(db.ForeignKey('Formulae.Id'), name='Formula_Id', index=True) formula = db.relationship('Formula') categories = db.relationship('Category', secondary='WorkTypeCategories') def to_json(self): return { 'id': self.id, 'name': self.name, 'GUID': self.guid, 'priceValue': self.price_value, 'salary': self.salary, 'time': self.time, 'order': self.order, 'descriptions': self.description, 'materialsCount': self.materials_count, 'formula': self.formula, 'categories': list(map(lambda c: {'id': c.id}, self.categories)) } @classmethod def from_json(cls, data): return WorkType(id=data.get('id', None), name=data['name'], guid=data['GUID'], price_value=data['priceValue'], salary=data['salary'], time=data['time'], order=data['order'], description=data['description'], materials_count=data['materialsCount'], formula=Formula.from_json(data['formula']))
class User(BaseObject, Model): email = Column(String(80), unique=True, nullable=False) password = Column(Binary(60), nullable=False) username = Column(String(80), nullable=False) home_mates = Column(Integer, nullable=True) footprints = db.relationship('Footprint', backref='user', lazy=True) activities = db.relationship('Activity', backref='user', lazy=True) dateCreated = Column(DateTime, nullable=False, default=datetime.utcnow) clearTextPassword = None def populateFromDict(self, dct): super(User, self).populateFromDict(dct) if dct.__contains__('password') and dct['password']: self.setPassword(dct['password']) def checkPassword(self, passwordToCheck): return bcrypt.hashpw(passwordToCheck.encode('utf-8'), self.password) == self.password def errors(self): errors = super(User, self).errors() if self.id is None \ and User.query.filter_by(email=self.email).count() > 0: errors.addError('email', 'Un compte lie a cet email existe deja') if self.email: errors.checkEmail('email', self.email) if self.clearTextPassword: errors.checkMinLength('password', self.clearTextPassword, 8) return errors def get_id(self): return str(self.id) def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def setPassword(self, newpass): self.clearTextPassword = newpass self.password = bcrypt.hashpw(newpass.encode('utf-8'), bcrypt.gensalt())
class Users(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), nullable=False, unique=True) name = db.Column(db.String, nullable=False) password = db.Column(db.String, nullable=False) vocabularys = db.relationship('Vocabularys') progress = db.relationship('Progress') news = db.relationship('News') topics = db.relationship('Topics', secondary=topic_identifier) # Create function to return String def __repr__(self): return self.id
class Email(db.Model): id: Optional[int] email: str url: str search_query: str sent_posts: Optional[List[Post]] id = db.Column(db.Integer, primary_key=True, autoincrement=True) email = db.Column(db.String(120)) url = db.Column(db.String(500)) search_query = db.Column(db.String(200)) sent_posts = db.relationship("Post", secondary=posts_identifier, cascade="all, delete") def __repr__(self): return "<Email %r>" % self.email def subscribe(self): db.session.add(self) db.session.commit() def unsubscribe(self): db.session.delete(self) db.session.commit()
class StoreModel(db.Model): __tablename__ = 'stores' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) items = db.relationship('InventoryModel', lazy='dynamic') def __init__(self, name): self.name = name def json(self): return {'name': self.name, 'items': [item.json() for item in self.items.all()]} @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class RoomType(db.Model): __tablename__ = 'RoomTypes' id = db.Column(db.Integer, name='Id', primary_key=True) name = db.Column(db.String(255), name='Name') guid = db.Column(db.String(255), name='GUID') image_path = db.Column(db.String(255), name='Image_Path', nullable=True) formulas = db.relationship('Formula', back_populates='room_type') def to_json(self): return { 'id': self.id, 'name': self.name, 'guid': self.guid, 'imagePath': self.image_path, 'formulas': self.formulas } def to_view_json(self): return {'id': self.id, 'name': self.name} @classmethod def from_json(cls, data): return cls(id=data.get('id', None), name=data['name'], guid=data['guid'], image_path=data['imagePath'], formulas=list(map(Formula.from_json, data['formulas'])))
class Activity(BaseObject, Model): user_id = Column(BigInteger, ForeignKey('user.id'), nullable=False) recommendation_id = Column(BigInteger, ForeignKey('recommendation.id'), nullable=False) recommendation = db.relationship('Recommendation', foreign_keys=[recommendation_id], backref='activity') date_start = Column(DateTime, nullable=False, default=datetime.utcnow()) date_end = Column(DateTime, nullable=True) is_success = Column(Boolean, nullable=True) status = Column(Enum(ActivityStatus), nullable=False, default=ActivityStatus.pending) def get_id(self): return str(self.id) def get_benefit(self): return self.recommendation.benefit def set_date_end(self): self.date_end = datetime.utcnow() def errors(self): errors = super(Activity, self).errors() return errors
class UserModel(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), nullable=False) posts = db.relationship('Post', backref='user', lazy=True) def __init__(self, name): self.name = name def json(self): return {'id': self.id, 'name': self.name} @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first() @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class Document(db.Model): __tablename__ = "Documents" id = db.Column(db.Integer, primary_key=True, name="Id", nullable=False) name = db.Column(db.String(255), name="Name", nullable=False) type = db.Column(db.Integer, name="DocumentType", nullable=False) date_created = db.Column(db.DateTime, name="DateCreated", nullable=False, default=datetime.now()) date_modified = db.Column(db.DateTime, name="DateModified", nullable=False, default=datetime.now()) project_id = db.Column(db.ForeignKey('MultiProjects.Id'), name='MultiProject_Id', index=True) rooms = db.relationship(Room, back_populates='document', cascade="all, delete-orphan") project = relationship('MultiProject') def to_view_json(self): return { 'id': self.id, 'name': self.name, 'dateCreated': str(self.date_created), 'dateModified': str(self.date_modified), 'documentType': self.type } def to_json(self): return { 'id': self.id, 'name': self.name, 'documentType': self.type, 'dateCreated': str(self.date_created), 'dateModified': str(self.date_modified), 'rooms': self.rooms } def update_from_json(self, data): self.name = data['name'] self.type = data['documentType'] self.date_modified = datetime.now() self.rooms = Room.array_from_json(data['rooms'], self.rooms) @classmethod def from_json(cls, data): return cls(name=data['name'], type=data['documentType'], rooms=list(map(Room.from_json, data['rooms'])))
class Category(db.Model): __tablename__ = 'Categories' id = db.Column( db.Integer, name='Id', primary_key=True ) order = db.Column( db.Integer, name='Order', nullable=False ) name = db.Column( db.String(255), name='Name' ) parent_id = db.Column( db.ForeignKey('Categories.Id'), name='Parent_Id', index=True ) parent = db.relationship('Category', remote_side=[id]) work_types = db.relationship('WorkType', secondary='WorkTypeCategories') def to_json(self): return { 'id': self.id, 'order': self.order, 'name': self.name, 'parent': {'id': self.parent_id} if self.parent_id is not None else None, 'workTypes': list(map(lambda wt: wt.id, self.work_types)) } @classmethod def from_json(cls, data): return cls( id=data.get('id', None), order=data['order'], name=data['name'], parent_id=data['parent'], work_types=WorkType.query.filter(WorkType.id in data['workTypes']) )
class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), nullable=False) comment = db.Column(db.String(255), nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) updated_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False, onupdate=datetime.now()) post = db.relationship("Post", backref=db.backref("posts", lazy=True)) def __init__(self, username, comment, post_id): self.username = username self.comment = comment self.post_id = post_id def json(self): return { "id": self.id, "username": self.username, "comment": self.comment, "post_id": self.post_id, "created_at": str(self.created_at), "updated_at": str(self.updated_at) } def create(self): db.session.add(self) db.session.commit() return self @classmethod def find_all(cls): comments = Comment.query.all() return [comment.json() for comment in comments] @classmethod def find_by_id(cls, id): return Comment.query.filter_by(id=id).first() @classmethod def delete(cls, id): comment = Comment.find_by_id(id) db.session.delete(comment) db.session.commit() return comment.json() @classmethod def update(cls, id, fields): comment = Comment.find_by_id(id) for key in field: setattr(comment, key, fields[key]) db.session.commit() return comment.json()
class PositionAccomplishment(ModelBase): position_id = db.Column( db.Integer, db.ForeignKey('resume_position.id', ondelete='CASCADE'), nullable=False, ) description = db.Column(db.Text, nullable=False) resume_position = db.relationship('ResumePosition', backref=db.backref('accomplishments', lazy='dynamic')) keywords = db.relationship('Keyword', secondary=accomplishment_keyword, backref=db.backref('accomplishments', lazy='dynamic'), lazy='dynamic')
class Hat(db.Model): __tablename__ = "hat" id = db.Column(db.Integer, primary_key=True) colour = db.Column(db.Enum(Colour)) char_id = db.Column(db.Integer, db.ForeignKey('character.id')) # Creates the one to one relationship character = db.relationship("Character", backref=db.backref("children", cascade="all,delete", passive_deletes=True)) def __init__(self, id, colour): self.id = id self.colour = colour
class Vendor(db.Model): __tablename__ = "db_vendor" id = db.Column(db.Integer, autoincrement=True, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('db_user.id'), nullable=False) user = db.relation(User, backref='vendor') name = db.Column(db.String(42), nullable=False) isFoundation = db.Column(db.Boolean, default=False, nullable=False) events = db.relationship(Event, secondary=vendor_event_table) def __repr__(self): return self.name
class Product(db.Model): __tablename__ = "db_product" id = db.Column(db.Integer, autoincrement=True, primary_key=True) vendor_id = db.Column(db.Integer, db.ForeignKey('db_vendor.id')) name = db.Column(db.String(42), nullable=False) price = db.Column(db.Float, nullable=False) vendor = db.relation(Vendor, backref='products') purchases = db.relationship('Purchase', secondary=product_purchase_table, back_populates="products") def __repr__(self): return self.name
class Vocabularys(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) topic_id = db.Column(db.Integer, db.ForeignKey('topics.id')) type = db.Column(db.String, nullable=False) origin = db.Column(db.String, nullable=False) translate = db.Column(db.String, nullable=False) progress = db.relationship('Progress') # Create function to return String def __repr__(self): return self.id
class ItemModel(db.Model): __tablename__ = "items" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) # precision=2, stands for the number of numbers after the decimal point. price = db.Column(db.Float(precision=2)) # stores is the table name of the store .id - column # foreign key reference is sort of "subsidiary" key, which has limited credentials. # basically now we give ID additional parameter, what store do we belong to? store_id = db.Column(db.Integer, db.ForeignKey("stores.id")) # Creates relationship between store id and every item in our database. store = db.relationship("StoreModel") def __init__(self, name, price, store_id): self.name = name self.price = price self.store_id = store_id def json(self): return { "id": self.id, "name": self.name, "price": self.price, "store_id": self.store_id } @classmethod def find_by_name(cls, name): # query is not something we have defined, it something that comes from db.Model # We have class. Then we say we want to query the model. And then we say filter by. # In other words SELECT * FROM items WHERE name=name(second name is our arg inside of find_by_name method) # Translates this code onto SQLCode, this data is also being converted to an item model object. return cls.query.filter_by(name=name).first() # SELECT * FROM items WHERE name=name LIMIT 1, basically returns only @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): # it is saving the model to the data base, SQLAlchemy can directly transform object to a row. # we are adding the collection of objects # this method is useful for both update and insert db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) username = db.Column(db.String(255), nullable=False) image = db.Column(db.String(255), nullable=False) description = db.Column(db.Text, nullable=False) bid = db.Column(db.Float, nullable=False) created_at = db.Column(db.DateTime, default=str(datetime.utcnow()), nullable=False) updated_at = db.Column(db.DateTime, default=datetime.utcnow(), nullable=False, onupdate=datetime.now()) user = db.relationship('User', backref=db.backref('users', lazy=True)) def __init__(self, user_id, username, image, bid, description): self.user_id = user_id self.username = username self.image = image self.bid = bid self.description = description def json(self): return { "id": self.id, "user_id": self.user_id, "username": self.username, "image": self.image, "bid": self.bid, "description": self.description, "created_at": str(self.created_at), "updated_at": str(self.updated_at) } def create(self): db.session.add(self) db.session.commit() return self @classmethod def find_all(cls): return Post.query.order_by(Post.bid.desc()).all() @classmethod def find_by_id(cls, post_id): post = Post.query.filter_by(id=post_id).first() return post
class Event(db.Model): __tablename__ = "db_event" id = db.Column(db.Integer, autoincrement=True, primary_key=True) date = db.Column(db.Date, nullable=False) location = db.Column(db.String, nullable=False) duff_value = db.Column(db.Float, nullable=False) name = db.Column(db.String, nullable=False) active = db.Column(db.Boolean, default=True, nullable=False) vendors = db.relationship('Vendor', secondary=vendor_event_table, back_populates="events") dummy_passport = db.Column(db.Integer, nullable=True) def __repr__(self): return '<Event %r>' % self.name
class MultiProject(db.Model): __tablename__ = 'MultiProjects' id = db.Column(db.Integer, name='Id', primary_key=True) name = db.Column(db.String(255), name='Name') documents = db.relationship('Document') def to_json(self): return {'id': self.id, 'name': self.name} @classmethod def from_json(cls, data): return cls(name=data['name'])
class Keyword(ModelBase): __table_args__ = (db.UniqueConstraint('user_id', 'keyword', name='keyword_user_unique'), ) user_id = db.Column( db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False, ) keyword = db.Column(db.String(50), nullable=False, index=True) user = db.relationship( 'User', backref=db.backref('keywords', lazy='dynamic'), )
class Contestant(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(256), nullable=False) insta = db.Column(db.String(256), nullable=False) image_url = db.Column(db.String(512), nullable=False) elimated_date = db.Column(db.DateTime, nullable=True) is_slops_crew = db.Column(db.Boolean) data_points = db.relationship( 'FollowerCountDataPoint', backref='user', lazy=True ) def __unicode__(self): return '<User %r>' % self.id def __repr__(self): return '<User %r>' % self.id
class User(db.Model): __tablename__ = 'user' id = db.Column( db.Integer, name='id', primary_key=True, nullable=False ) name = db.Column( db.String(100), name='name', unique=True, nullable=False ) email = db.Column( db.String(100), name='email', nullable=False, unique=True ) password = db.Column( db.String(100), name='password', nullable=False ) roles = db.relationship( "Role", secondary='user_role', backref=db.backref('user'), single_parent=True ) def set_password(self, password): """Set password.""" bcrypt = Bcrypt(current_app) self.password = bcrypt.generate_password_hash(password) def check_password(self, value): """Check password.""" bcrypt = Bcrypt(current_app) return bcrypt.check_password_hash(self.password, value)
class StoreModel(db.Model): __tablename__ = "stores" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) # SQLAlchemy creates a relationship between ItemModel # this variable is the item list. Because it knows there can be a lot of items with the same store ID. # if we have a lot of items, we can tell SQLAlchemy do not go into the items table and create # an object for each item yet. (lazy="dynamic") items = db.relationship("ItemModel", lazy="dynamic") def __init__(self, name): self.name = name def json(self): # .all() is only used with lazy="dynamic". It makes self.items no longer a list of items # but a query builder that has the ability to look into the items table, then we can use .all() # to retrieve all items from that table. Which means that until we call the JSON method # we are not looking into the table. Which means that creating stores is very simple. # However, whenever we call the JSON method, we have to go into the table, it gonna be slower. return { "id": self.id, "name": self.name, "items": [item.json() for item in self.items.all()] } @classmethod def find_by_name(cls, name): # SELECT * FROM items WHERE name=name LIMIT 1, basically returns only return cls.query.filter_by(name=name).first() @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): # it is saving the model to the data base, SQLAlchemy can directly transform object to a row. # we are adding the collection of objects # this method is useful for both update and insert db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class ApplicationEvent(ModelBase): application_id = db.Column( db.Integer, db.ForeignKey('application.id', ondelete='CASCADE'), nullable=False, ) event_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) event_type = db.Column(db.String(255), nullable=False, index=True) event_description = db.Column(db.String(255), nullable=False, index=True) application_notes = db.Column(db.Text, nullable=True) contacts = db.relationship('ApplicationContact', secondary=event_contacts, backref=db.backref('events', lazy='dynamic'), lazy='dynamic')
class Character(db.Model): __tablename__ = "character" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128)) age = db.Column(db.Integer) weight = db.Column(db.Float) human = db.Column(db.Boolean) hat = db.Column(db.Integer) # Creates the one to one relationship hat_R = db.relationship('Hat', uselist=True, back_populates="character") def __init__(self, id, name, age, weight, human, hat): self.id = id self.name = name self.age = age self.weight = weight self.human = human self.hat = hat
class Users(db.Model, UserMixin): """This is User class for table structure.""" __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(80), unique=True, nullable=False) image_file = db.Column(db.String(20), nullable=False, default='default.jpg') password = db.Column(db.String(60), nullable=False) recipes = db.relationship('Recipes', backref='author', lazy=True) is_active = db.Column(db.Boolean, default=True) role = db.Column(db.Integer, default='2') def get_reset_token(self, expires_sec=1800): """Get reset token for change the password.""" return jwt.encode( { 'reset_password': self.id, 'exp': time() + expires_sec }, app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8') @staticmethod def verify_reset_token(token): """Verify reset token for change the password.""" try: id = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password'] except: return return Users.query.get(id) def __rerp__(self): """Representation string of an Users object.""" return f"Users('{self.username}', " \ f"'{self.email}', " \ f"'{self.image_file}'," \ f"'{self.is_active}'," \ f"'{self.role}')"