class User(database.Model, UserMixin): __tablename__ = "user" id = database.Column("id", database.Integer, primary_key=True, autoincrement=True) username = database.Column("username", database.String(255), unique=True, nullable=False) password = database.Column("password", database.Text, nullable=False) email = database.Column("email", database.String(255), unique=True, nullable=False) posts = database.relationship("Post", backref="poster") sentMessages = database.relationship("Message", backref="sender", lazy="dynamic", foreign_keys="Message.senderId") receivedMessages = database.relationship("Message", backref="receiver", lazy="dynamic", foreign_keys="Message.receiverId") def __init__(self, username, password, email): self.username = username self.password = password self.email = email
class Project(db.Model): """Represents table holding all projects""" __tablename__ = 'project' id = db.Column(db.Integer, autoincrement=True, primary_key=True) name = db.Column(db.String(25), nullable=False) description = db.Column(db.Text(), nullable=False) owner_id = db.Column(db.Integer, db.ForeignKey('user_data.id'), nullable=False) # Dataset is parent of view, thus this relationship helper class datasets = db.relationship('Dataset', backref=backref('project'), lazy='dynamic', passive_deletes=True ) # Project has a many-to-many relationship with User # passive_deletes = True to make cascade on delete work correctly # otherwise we get SET NULL-like behaviour users = db.relationship("Access", backref='project', passive_deletes=True) def __init__(self, name, descr, creator): self.name = name self.description = descr self.owner_id = creator
class User(database.Model, UserMixin): id = database.Column(database.Integer, primary_key=True) name = database.Column(database.String(255)) last_name = database.Column(database.String(255)) email = database.Column(database.String(255), unique=True) password_hash = database.Column(database.String(255)) active = database.Column(database.Boolean(), default=False) roles = database.relationship( 'Role', secondary=roles_users, ) seances_and_users = database.relationship( 'Seance', secondary=seances_and_users, cascade="all,delete", backref=database.backref('users_on_seance', passive_deletes=True) ) def __str__(self): return "{} {}".format(self.name, self.last_name) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def push_user_to_database_and_set_role(self): from app import user_datastore user_datastore.create_user(name=self.name, last_name=self.last_name, email=self.email, password_hash=self.password_hash, active=False) user_datastore.add_role_to_user(self.email, 'user')
class Registration(database.Model): def __init__(self, user, tour, date, paid): self.user = user self.tour = tour self.date = date self.isPaid = paid __tablename__ = 'registrations' id = database.Column(database.Integer, primary_key=True) tour_id = database.Column(database.Integer, database.ForeignKey('tours.id'), nullable=False) tour = database.relationship('Tour', backref=database.backref('registrations', lazy='dynamic')) user_id = database.Column(database.Integer, database.ForeignKey('users.id'), nullable=False) user = database.relationship('User', backref=database.backref('registrations', lazy='dynamic')) date = database.Column(database.DateTime) isPaid = database.Column(database.Boolean) def __repr__(self): return '<Registration \'{}\'>'.format(self.id)
class User(UserMixin, database.Model): """User account model.""" __tablename__ = 'flasklogin-users' id = database.Column(database.Integer, primary_key=True) name = database.Column(database.String(100), nullable=False, unique=False) email = database.Column(database.String(40), unique=True, nullable=False) role = database.Column(database.String(40), unique=True, nullable=False) password = database.Column(database.String(200), primary_key=False, unique=False, nullable=False) enrolled = database.relationship("EduSchedu", secondary=student_identifier, backref=database.backref('enrolled'), lazy='dynamic') approlled = database.relationship("ApptSchedu", secondary=student_appt, backref=database.backref('approlled'), lazy='dynamic') def avatar(self, size): digest = md5(self.email.lower().encode('utf-8')).hexdigest() return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format( digest, size) def set_password(self, password): self.password = generate_password_hash(password, method='sha256') def check_password(self, password): return self.password def __repr__(self): return "%s" % (self.name)
class Sbc(db.Model): __tablename__ = 'sbc' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) connected = db.Column(db.Boolean) description = db.Column(db.Text) # Foreign keys: logs = db.relationship('Logs', cascade="all, delete", backref='sbc', lazy=True) forwarding = db.relationship('Forwarding', cascade="all, delete", backref="sbc", lazy=True)
class Team(PkModel): """A role for a user.""" __tablename__ = "team" id = Column(db.Integer, primary_key=True) name = Column(db.String(80)) players = relationship("Player", backref="team", lazy=True) division = Column(db.Integer) matches = relationship("Match", backref="team", lazy=True) player_stats = relationship("PlayerStat", backref="team", lazy=True) event_id = db.Column(db.Integer, db.ForeignKey('event.id'), nullable=False) def __init__(self, name, **kwargs): """Create instance.""" super().__init__(**kwargs) def __repr__(self): return "Team {}, {} Rating".format(self.name, self.rating) async def refresh_stats(self, startTimestamp=None, endTimestamp=None): all_matches = await get_matches_for_team(self, startTimestamp=startTimestamp, endTimestamp=endTimestamp) for match in all_matches: player_stats = [] match_data = json.dumps(match) match_data = json.loads(match_data) for stat in match_data['stats']: player_stat = PlayerStat(stat['player']['uno'], stat['playerStats']['kills'], stat['playerStats']['teamPlacement']) player_stats.append(player_stat) match = Match(match_data['id'], player_stats) self.add_match(match) #for stat in stats: # player_kills = stat['playerStats']['kills'] # team_placement = stat['playerStats']['teamPlacement'] #asyncio.get_event_loop().run_until_complete(get_team_matches(self)) #asyncio.run(get_team_matches(self)) def add_match(self, match): if self.matches is None: self.matches = [] if match.external_id in [match.external_id for match in self.matches]: return self.matches.append(match) print("added match {}".format(match.external_id)) @property def rating(self): rating = 0 for match in self.matches: for stat in match.player_stats: rating += stat.kills return rating
class UserProfile(Model, SurrogatePK): __tablename__ = 'userprofile' # id is needed for primary join, it does work with SurrogatePK class id = db.Column(db.Integer, primary_key=True) user_id = reference_col('users', nullable=False) user = relationship('User', backref=db.backref('profile', uselist=False)) follows = relationship('UserProfile', secondary=followers_assoc, primaryjoin=id == followers_assoc.c.follower, secondaryjoin=id == followers_assoc.c.followed_by, backref='followed_by', lazy='dynamic') def __init__(self, user, **kwargs): db.Model.__init__(self, user=user, **kwargs) def is_following(self, profile): return bool(self.follows.filter(followers_assoc.c.followed_by == profile.id).count()) def follow(self, profile): if self is not profile and not self.is_following(profile): self.follows.append(profile) return True return False def unfollow(self, profile): if self is not profile and self.is_following(profile): self.follows.remove(profile) return True return False @property def following(self): if current_user: return current_user.profile.is_following(self) return False @property def username(self): return self.user.username @property def bio(self): return self.user.bio @property def image(self): return self.user.image @property def email(self): return self.user.email
class Users(database.Model): id = database.Column(database.Integer, primary_key=True) username = database.Column(database.String(64), index=True, unique=True) common_name = database.Column(database.String(64)) email = database.Column(database.String(120)) password_hash = database.Column(database.String(128)) token = database.Column(database.String(32), index=True, unique=True) token_expiration = database.Column(database.DateTime) posts = database.relationship('Post', backref='author', lazy='dynamic') threads = database.relationship( 'Thread', backref='creator', lazy='dynamic' ) forums = database.relationship('Forum', backref='creator', lazy='dynamic') def __repr__(self): return '<User {}>'.format(self.username) def from_dict(self, data, new_user=False): for field in ['username', 'email', 'common_name']: if field in data: setattr(self, field, data[field]) if new_user and 'password' in data: self.set_password(data['password']) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def get_token(self, expires_in=SECONDS_PER_DAY): now = datetime.utcnow() if self.token and self.token_expiration > now + timedelta(seconds=60): return self.token self.token = base64.b64encode(os.urandom(24)).decode('utf-8') self.token_expiration = now + timedelta(seconds=expires_in) update_token_query = f""" UPDATE users SET token='{self.token}', token_expiration='{self.token_expiration}' WHERE users.id = '{self.id}' """ database.session.execute(update_token_query) return self.token @staticmethod def check_token(token): user = Users.query.filter_by(token=token).first() print(f'Find a token {token} for user {user}') if user is None or user.token_expiration < datetime.utcnow(): print(f'Invalid token') return None return user
class Role(database.Model): id = database.Column(database.Integer, primary_key=True) name = database.Column(database.String(64), unique=True) default = database.Column(database.Boolean, default=False, index=True) permissions = database.Column(database.Integer) users = database.relationship("User", backref="role", lazy="dynamic") companies = database.relationship("Company", backref="role", lazy="dynamic") def __init__(self, **kwargs): super(Role, self).__init__(**kwargs) if self.permissions is None: self.permissions = 0 def add_permission(self, permission): if not self.has_permission(permission): self.permissions += permission def has_permission(self, permission): return self.permissions and permission == permission @staticmethod def insert_roles(): default_role = "User" roles = { "User": [ Permission.COMMENT, Permission.WRITE_ARTICLES, Permission.MODERATE_COMMENTS ], "Company": [ Permission.COMMENT, Permission.WRITE_ARTICLES, Permission.MANAGE_PRODUCTS ] } for r in roles: role = Role.query.filter_by(name=r).first() if role is None: role = Role(name=r) role.reset_permissions() for permission in roles[r]: role.add_permission(permission) role.default = (role.name == default_role) database.session.add(role) database.session.commit() def remove_permission(self, permission): if self.has_permission(permission): self.permissions -= permission def reset_permissions(self): self.permissions = 0
class Article(database.Model): __searchable__ = ["title", "body"] id = database.Column(database.Integer, primary_key=True) title = database.Column(database.String(100), nullable=False, unique=True) date_posted = database.Column(database.DateTime, nullable=False, default=datetime.utcnow) body = database.Column(database.Text, nullable=False) user_id = database.Column(database.Unicode(36), database.ForeignKey("user.id"), nullable=False) company_id = database.Column(database.Unicode(36), database.ForeignKey("company.id"), nullable=True) image_file = database.Column(database.String(150), unique=False, nullable=True, default="/static/homepagePics/blackgirls.jpg") comments = database.relationship("Comment", cascade="all,delete", backref="article", lazy="dynamic") likes = database.relationship("Like", cascade="all,delete", backref="article", lazy="dynamic") views = database.Column(database.Integer, default=0) @staticmethod def generate_fake(): from random import seed, randint import forgery_py seed() user_count = User.query.count() company_count = Company.query.count() for i in range(user_count): user = User.query.offset(randint(0, user_count - 1)).first() company = Company.query.offset(randint(0, company_count - 1)).first() article = Article(title=forgery_py.lorem_ipsum.words(randint(1, 5)), body=forgery_py.lorem_ipsum.sentences( randint(1, 3)), author=user, company=company) database.session.add(article) database.session.commit() def __repr__(self): return "Article('{}', '{}')".format(self.title, self.date_posted)
class Group(SurrogateBaseKey, Model): """User Group""" __tablename__ = 'groups' name = Column(db.String(20), unique=True, nullable=False) users = relationship( 'User', secondary=GROUPS_USERS, lazy='subquery', backref=db.backref('groups', lazy=True)) permissions = relationship( 'Permission', secondary=GROUPS_PERMISSIONS, lazy='subquery', backref=db.backref('groups', lazy=True)) def __repr__(self): return '<Group %r>' % self.name
class Account(database.Model): id = database.Column(database.Integer, primary_key=True) level = database.Column(database.Integer, nullable=False) username = database.Column(database.String(16), unique=True, nullable=False) start_date = database.Column(database.DateTime, nullable=False) last_queried = database.Column(database.DateTime, server_default=database.func.now(), server_onupdate=database.func.now()) create_date = database.Column(database.DateTime, server_default=database.func.now()) modify_date = database.Column(database.DateTime, server_onupdate=database.func.now()) assignments = database.relationship('Assignment', backref='user', lazy='dynamic') levels = database.relationship('LevelProgression', backref='user', lazy='dynamic') reviews = database.relationship('Review', backref='user', lazy='dynamic') def __repr__(self): return f'<User {self.username}, Level {self.level}>'
class Product(database.Model): __searchable__ = ["name", "price"] id = database.Column(database.Integer, primary_key=True) name = database.Column(database.String(50), unique=True, nullable=False) price = database.Column(database.Integer, nullable=False, default=0.00) rating = database.Column(database.Integer, nullable=True, default=5) description = database.Column(database.Text, nullable=False) image_file = database.Column( database.String(150), unique=False, nullable=True, default="/static/profilePics/default_" + str(random.randint(1, len(os.listdir("app/static/profilePics")) + 1)) + ".jpg") date_posted = database.Column(database.DateTime, nullable=False, default=datetime.utcnow) company_id = database.Column(database.Unicode(36), database.ForeignKey("company.id"), nullable=True) reviews = database.relationship("Review", cascade="all,delete", backref="product", lazy="dynamic") wishlist = database.relationship("User", secondary=items, backref=database.backref("wishlist", lazy="dynamic")) @staticmethod def generate_fake(): from random import seed import forgery_py seed() company_count = Company.query.count() for i in range(company_count): company = Company.query.offset(randint(0, company_count - 1)).first() product = Review(name=forgery_py.lorem_ipsum.words(randint(1, 3)), price=forgery_py.monetary.money(), description=forgery_py.lorem_ipsum.sentences( randint(1, 3)), company=company) database.session.add(product) database.session.commit()
class Notification(database.Model): def __init__(self, to_user, subject_, message, date_): self.to_user_id = to_user self.subject = subject_ self.message = message self.date = date_ self.read = 0 __tablename__ = 'notification' id = database.Column(database.Integer, primary_key=True) to_user_id = database.Column(database.Integer, database.ForeignKey('users.id'), nullable=False) to_user = database.relationship('User', backref=database.backref('notification', lazy='dynamic')) date = database.Column(database.DateTime, nullable=False) message = database.Column(database.Text) read = database.Column(database.Integer) subject = database.Column(database.Text) def __repr__(self): return '<Notification \'{}\'>'.format(self.id)
class User(db.Model, UserMixin): """Represents table holding user data in our database""" # Table name to be used in database # If not provided class name is used which is a problem when using # postgres because user is a reserved keyword __tablename__ = 'user_data' # Table columns id = db.Column(db.Integer, autoincrement=True, primary_key=True) first_name = db.Column(db.String(25)) last_name = db.Column(db.String(25)) email = db.Column(db.String(50), unique=True, nullable=False) username = db.Column(db.String(20), unique=True, nullable=False) password = db.Column(db.String(80), nullable=False) admin = db.Column(db.Boolean(), default=0) disabled = db.Column(db.Boolean(), default=0) # User is parent of action, thus this relationship helper class actions = db.relationship('Action', backref='user', lazy='dynamic') def __init__(self, fname, lname, email, uname, password): """Initializes a user instance""" self.first_name = fname self.last_name = lname self.email = email self.username = uname self.password = generate_password_hash(password, method='sha256')
class State(Model): __tablename__ = 'states' id = Column(db.Integer, primary_key=True) abv = Column(db.String()) name = Column(db.String()) color = Column(db.String()) records = relationship('Record', backref='state', lazy='dynamic')
class User(db.Model): id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index = True, unique=True) #how we relate this user to all of its many posts posts = db.relationship('Post', backref='author', lazy='dynamic') @property def is_authenticated(self): return True @property def is_active(self): return True @property def is_anonymous(self): return False def get_id(self): try: return unicode(self.id) # python 2 except NameError: return str(self.id) # python 3 def __repr__(self): return '<User %r>' % self.nickname
class Event(database.Model): __tablename__ = 'event' plug_in_event_id = database.Column(database.BigInteger, primary_key=True) start_date = database.Column(database.DateTime, nullable=False) start_time_zone = database.Column(database.String(3), nullable=False) end_date = database.Column(database.DateTime, nullable=False) end_time_zone = database.Column(database.String(3), nullable=False) transaction_date = database.Column(database.DateTime, nullable=False) total_duration = database.Column(database.Time, nullable=False) charging_time = database.Column(database.Time, nullable=False) energy = database.Column(database.Float, nullable=False) ghg_savings = database.Column(database.Float, nullable=False) gasoline_savings = database.Column(database.Float, nullable=False) currency = database.Column(database.String(3)) fee = database.Column(database.SmallInteger) ended_by = database.Column(database.String(30)) user_id = database.Column(database.Integer, index=True) driver_postal_code = database.Column(database.String(5)) station_name = database.Column(database.String(30), index=True, primary_key=True) port_number = database.Column(database.SmallInteger, nullable=False) port = database.relationship('Port', backref='events') __table_args__ = (database.ForeignKeyConstraint( ['port_number', 'station_name'], ['port.port_number', 'port.station_name']), ) def __repr__(self): return '<Event {}, {}>'.format(self.plug_in_event_id, self.station_name)
class Session(Model): __tablename__ = 'sessions' id = Column(db.Integer, primary_key=True) user_id = Column(db.Integer, db.ForeignKey('users.id')) timestamp = Column(db.DateTime, default=datetime.utcnow) type = Column(db.String(32)) routes = relationship('Route', backref='session', lazy='dynamic')
class Dataset(db.Model): """ Represents table holding dataset info """ __tablename__ = 'dataset' id = db.Column(db.Integer, autoincrement=True, primary_key=True) name = db.Column(db.String(50), nullable=False) original_data = db.Column(db.String(50), unique=True, nullable=False) working_copy = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.String(255), nullable=False) # View is parent of action, thus this relationship helper class actions = db.relationship('Action', backref='dataset', lazy='dynamic', passive_deletes=True) # Dataset is child of project, thus this foreign key project_id = db.Column(db.Integer, db.ForeignKey('project.id', ondelete='CASCADE')) def __init__(self, name, original, working, description, project): self.name = name self.original_data = original self.working_copy = working self.description = description self.project_id = project
class User(database.Model, UserMixin): id = database.Column(database.Integer, primary_key=True) email = database.Column(database.String(100), unique=True) password = database.Column(database.String(255)) active = database.Column(database.Boolean) roles = database.relationship( 'Role', secondary=user_role_relation_database, backref=database.backref('users'), lazy='dynamic' )
class Role(Model): __tablename__ = 'roles' id = Column(db.Integer, primary_key=True) name = Column(db.String(64), unique=True) users = relationship('User', backref='role', lazy='dynamic') def __repr__(self): return f'<Role {self.name}, {self.id}>'
class Forum(database.Model): id = database.Column(database.Integer, primary_key=True) name = database.Column(database.String(64), index=True, unique=True) short_name = database.Column(database.String(32), index=True, unique=True) creator_id = database.Column( database.Integer, database.ForeignKey('users.id') ) threads = database.relationship('Thread', backref='forum', lazy='dynamic')
class Document(database.Model): __tablename__ = 'document' id_document = database.Column(database.Integer, primary_key=True) document_name = database.Column(database.String(40)) rubric = database.Column(database.String(140)) description = database.Column(database.String(1000)) status = database.Column(database.Float()) path_to_file = database.Column(database.String(256)) path_to_xml_file = database.Column(database.String(256)) path_to_instruction = database.Column(database.String(256)) # relation_with_document = database.relationship('Relation', backref='author', lazy='dynamic') document_to_relation = database.relationship( 'Relation', backref='documents_to_relation') document_to_attribute = database.relationship( 'Attribute', backref='document_to_attribute') def __repr__(self): return '<Document {}>'.format(self.path_to_file) def get_id(self): return self.id_document def get_name(self): return self.document_name def get_status(self): return self.status def get_rubric(self): return self.rubric def get_instruction(self): return self.path_to_instruction def get_text(self): return self.path_to_file def get_xml(self): return self.path_to_xml_file def get_description(self): return self.description
class Role(SurrogatePK, Model): __tablename__ = 'roles' name = Column(db.String(80), unique=True, nullable=False) user_id = ReferenceCol('users', nullable=True) user = relationship('User', backref='roles') def __init__(self, name, **kwargs): db.Model.__init__(self, name=name, **kwargs) def __repr__(self): return '<Role({name})>'.format(name=self.name)
class EduSchedu(database.Model): __tablename__ = 'classes' id = database.Column(database.Integer, primary_key=True) time = database.Column(TIME(), nullable=False) dow = database.Column(database.Integer, default='') classname = database.Column(database.String(100), default='') zoomlink = database.Column(database.String(500), default='') students = database.relationship("User", secondary=student_identifier, backref=database.backref('students'), lazy='dynamic')
class Organisation(SurrogatePK, Model): """docstring for ClassName""" __tablename__ = 'organisations' uuid = Column(db.String(36), unique=True, nullable =False ) code = Column(db.String(3), unique=True, nullable=False) vrn = Column(db.String(9), unique=True) name = Column(db.String(50), unique=True) # Relationships users = relationship('User', backref='organisation') vat_returns = relationship('Vat_return', backref='organisation') def __init__(self, code, **kwargs): self.uuid = str(uuid.uuid4()) db.Model.__init__(self, code=code, **kwargs) def __repr__(self): """Represent instance as a unique string.""" return '<Organisation({name})>'.format(name=self.name)
class Message(SurrogatePK, Model): __tablename__ = 'messages' user_id = Column(db.Integer, db.ForeignKey('users.id')) body = Column(db.String(140)) timestamp = Column(db.DateTime(timezone=True), index=True, default=maya.now().datetime) user = relationship('User', back_populates='messages', lazy='joined') def __repr__(self): return '<Message {}>'.format(self.body)
class User(db.Model, UserMixin): """ Database Model for Table Users """ id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) todos = db.relationship("Todo", backref="owner") def set_password(self, password: str): """ Set the hashed password for the user """ self.password_hash = generate_password_hash(password) def check_password(self, password: str): """ Check the users password """ return check_password_hash(self.password_hash, password) def is_active(self): """ True, as all users are active. """ return True def get_id(self): """ Return the email address to satisfy Flask-Login's requirements. """ return self.id def is_authenticated(self): """ Return True if the user is authenticated. """ return self.authenticated def is_anonymous(self): """ False, as anonymous users aren't supported. """ return False def __repr__(self): return f"{self.username} -> {self.email}" def remove_todo(self, task: str): """ Remove Todo from the user """ for i in self.todos: if i.task == task: db.session.delete(i) db.commit() else: continue def add_todo(self, task: str): """ Add Todo to the user """ td = Todo(task=task, owner=User.query.filter_by(username=self.username).first()) db.session.add(td) db.session.commit()