class User(db.Model, UserMixin, CRUDMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(30), unique=True, index=True) password_hash = db.Column(db.String(128)) cs = db.relationship('CS', backref='user', lazy=True, cascade="all,delete") rating = db.relationship('Rating', backref='user', lazy=True, cascade="all,delete") def __repr__(self): return '<User %r>' % self.username @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password)
class Users(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True) surname = db.Column(db.String(64), index=True) email = db.Column(db.String(120), index=True, unique=True) is_admin = db.Column(db.Boolean(), default=False) paper = db.relationship('Papers', backref='proposer', lazy='dynamic') schedule = db.relationship('Schedules', backref='speaker', lazy='dynamic') def __repr__(self): return '<User {}>'.format(self.surname)
class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(128), index=True, unique=True) password_hash = db.Column(db.String(128)) posts = db.relationship('Post', backref='author', lazy='dynamic') about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime, default=datetime.utcnow) followed = db.relationship('User', secondary=followers, primaryjoin=(followers.c.follower_id == id), secondaryjoin=(followers.c.followed_id == id), backref=db.backref('followers', lazy='dynamic'), lazy='dynamic') def __repr__(self): return "<User {}>".format(self.username) 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 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 follow(self, user): if not self.is_following(user): self.followed.append(user) def unfollow(self, user): if self.is_following(user): self.followed.remove(user) def is_following(self, user): return self.followed.filter( followers.c.followed_id == user.id).count() > 0 def followed_posts(self): followed = Post.query.join( followers, (followers.c.followed_id == Post.user_id)).filter( followers.c.follower_id == self.id) own = Post.query.filter_by(user_id=self.id) return followed.union(own).order_by(Post.timestamp.desc())
class Recipe(db.Model): __tablename__ = 'recipes' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(16), unique=True, nullable=False) default = db.Column( db.Boolean ) # initialize this to 1 if you're adding a default meal to the database, custom meals will be 0 ingredients = db.relationship('Ingredient', secondary=ing_rec_assc) def cumulative_neg_attributes(self): """ Total number of negative attributes across all ingredients """ count = 0 for ing in self.ingredients: for att in ing.attributes: if not att: count += 1 return count def cumulative_pos_attributes(self): """ Total number of negative attributes across all ingredients """ count = 0 for ing in self.ingredients: for att in ing.attributes: if att: count += 1 return count
class CostGroup(db.Model): __tablename__ = 'cost_groups' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) group_id = db.Column(db.Integer, db.ForeignKey('groups.id'), nullable=False) group_member = db.relationship('User', backref='group', lazy=True) def __init__(self, user_id, group_id): self.user_id = user_id self.group_id = group_id def to_json(self): json_memberships = {'user_id': self.user_id, 'group_id': self.group_id} return json_memberships @staticmethod def from_json(memberships_json): try: user_id = memberships_json.get('user_id') group_id = memberships_json.get('group_id') if user_id is None or group_id is None: return None return CostGroup(user_id, group_id) except AttributeError: return None
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) image_file = db.Column(db.String(20), nullable=False, default='default.jpg') password = db.Column(db.String(60), nullable=False) posts = db.relationship('Post', backref='author', lazy=True) # generating the password reseting roken def get_reset_token(self, expires_sec=1800): s = Serializer(current_app.config['SECRET_KEY'], expires_sec) return s.dumps({'user_id': self.id}).decode('utf-8') # verify the token if the token has exprired or invalid @staticmethod def verify_reset_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: user_id = s.loads(token)['user_id'] except: return None return User.query.get(user_id) def __repr__(self): return f"User('{self.username}', '{self.email}', '{self.image_file}')"
class Groups(db.Model): __tablename__ = 'groups' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), nullable=False, unique=True) cost_group = db.relationship('CostGroup', backref='cost_group', lazy=True) def __init__(self, name): self.name = name def to_json(self): json_group = { 'url': url_for('api.get_group', id=self.id, _external=True), 'name': self.name, 'costs': url_for('api.group_costs', id=self.id, _external=True), 'debt_table': url_for('api.debt_table', id=self.id, _external=True) } return json_group @staticmethod def from_json(group_json): try: name = group_json.get('name') if name is None: return None return Groups(name) except AttributeError: return None
class Client(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), index=True) request = db.relationship('Request', backref='client', lazy='dynamic') # def __repr__(self): # return '<Client %r>' % (self.name) def __repr__(self): return f"<Client(name='{self.name}')>"
class Papers(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(400), index=True) url = db.Column(db.String(200), index=True) doi = db.Column(db.String(100), index=True) proposer_id = db.Column(db.Integer, db.ForeignKey('users.id')) schedule = db.relationship('Schedules', backref='paper', lazy='dynamic') def __repr__(self): return '<Paper {}>'.format(self.title)
class Ingredient(db.Model): __tablename__ = 'ingredients' ing_id = db.Column(db.Integer, primary_key=True) ing_name = db.Column(db.String(12), unique=True, nullable=False) ing_fg_id = db.Column(db.Integer, db.ForeignKey('food_groups.fg_id'), nullable=False) ing_desc = db.Column(db.String(255), unique=False, nullable=True) ing_pic = db.Column(db.String(255), unique=False, nullable=True) food_group = db.relationship('Food_Group') attributes = db.relationship('Attribute', secondary=ing_att_assc) recipes = db.relationship('Recipe', secondary=ing_rec_assc) def __repr__(self): return '<Ingredient %r>' % self.ing_name def num_pos_attributes(self): """ Returns the number of postitive attributes belonging to the ingredient """ count = 0 for attr in self.attributes: if attr.att_pos_neg: count+=1 return count def num_neg_attributes(self): """ Returns the number of negative attributes belonging to the ingredient """ count = 0 for attr in self.attributes: if not attr.att_pos_neg: count+=1 return count def rendered_image(self): """ Wraps the image in HTML to be rendered in the table view later """ html = '<img src="'+self.ing_pic+ '"width="160" height="160" alt="'+self.ing_name+ '" title="'+self.ing_name+ '" >' return Markup(html)
class Food_Group(db.Model): """ Class which accesses the DB table for food groups """ __tablename__ = 'food_groups' fg_id = db.Column(db.Integer, primary_key=True) # Unique ID, autoincrement, primary key fg_name = db.Column(db.String(12), unique=True, nullable=False) # Name of the food group, must be unique (there should only ever be 5) ingredients = db.relationship('Ingredient', backref='fg') # Notate DB relationship b/w ingredients and food group def __repr__(self): return self.fg_name # What is printed when the class is queried (required)
class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) default = db.Column(db.Boolean, default=False, index=True) permissions = db.Column(db.Integer) users = db.relationship('User', backref='role', lazy='dynamic') def __init__(self, **kwargs): super(Role, self).__init__(**kwargs) if self.permissions is None: self.permissions = 0 @staticmethod def insert_roles(): roles = { 'User': [Permission.COST, Permission.WRITE], 'Moderator': [Permission.COST, Permission.WRITE, Permission.MODERATE], 'Administrator': [ Permission.COST, Permission.WRITE, Permission.MODERATE, Permission.ADMIN ], } default_role = 'User' for r in roles: role = Role.query.filter_by(name=r).first() if role is None: role = Role(name=r) role.reset_permissions() for perm in roles[r]: role.add_permission(perm) role.default = (role.name == default_role) db.session.add(role) db.session.commit() def add_permission(self, perm): if not self.has_permission(perm): self.permissions += perm def remove_permission(self, perm): if self.has_permission(perm): self.permissions -= perm def reset_permissions(self): self.permissions = 0 def has_permission(self, perm): return self.permissions & perm == perm def __repr__(self): return '<Role %r>' % self.name
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) image_file = db.Column(db.String(20), default='default.jpeg', nullable=False) password = db.Column(db.String(60), nullable=False) posts = db.relationship('Post', backref='author', lazy=True) def __repr__(self): return "User('%s','%s','%s')" % (self.username, self.email, self.image_file)
class Role(db.Model): """ Create a Role table """ __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60), unique=True) description = db.Column(db.String(200)) employees = db.relationship('Employee', backref='role', lazy='dynamic') def __repr__(self): return '<Role: {}>'.format(self.name)
class Rating(db.Model, CRUDMixin): __tablename__ = 'ratings' id = db.Column(db.Integer, primary_key=True) pos_weight = db.Column(db.Integer, nullable=False) nps_weight = db.Column(db.Integer, nullable=False) fz_weight = db.Column(db.Integer, nullable=False) refund_fz_weight = db.Column(db.Integer, nullable=False) sms_weight = db.Column(db.Integer, nullable=False) kr_weight = db.Column(db.Integer, nullable=False) box_weight = db.Column(db.Integer, nullable=False) ops_weight = db.Column(db.Integer, nullable=False) date = db.Column(db.DateTime, default=datetime.datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='cascade'), nullable=False) employees = db.relationship('ArchiveCS', secondary='association', back_populates='rating_id', cascade="all,delete") def __repr__(self): return f'Рейтинг от {self.date}' @property def weight_serialize(self): return { 'pos_weight': self.pos_weight, 'nps_weight': self.nps_weight, 'fz_weight': self.fz_weight, 'refund_fz_weight': self.refund_fz_weight, 'sms_weight': self.sms_weight, 'kr_weight': self.kr_weight, 'box_weight': self.box_weight, 'ops_weight': self.ops_weight } @property def format_date_(self): if sys.platform == 'win32': locale.setlocale(locale.LC_ALL, 'rus_rus') else: locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') format_ = datetime.datetime.strftime(self.date, '%d %B %Y') return format_
class Users(db.Model, UserMixin): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) firstName = db.Column(db.String(50), nullable=True) lastName = db.Column(db.String(50), nullable=True) position = db.Column(db.String(50), nullable=True) email = db.Column(db.String(120), nullable=True) # Define relationship between Users and Role using secondary table UserRoles # By referencing the secondary table, it is unnecessary to specify a relationship # between the Role and UserRole table roles = db.relationship( "Role", backref="users", lazy=True, passive_deletes=True, secondary="user_roles", ) def __repr__(self): return f"Users('{self.firstName}','{self.lastName}','{self.email}')"
class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), nullable=False, index=True, unique=True) email = db.Column(db.String(64), nullable=False, unique=True, index=True) password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) profile_image = db.Column(db.String(128), nullable=False, default='default_profile_img.png') costs = db.relationship('Costs', backref='author', lazy=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) needs = db.relationship('Needs', backref='author', lazy=True) memberships = db.relationship('CostGroup', backref='user', lazy=True) def __init__(self, username, email, password): self.username = username self.email = email self.password_hash = generate_password_hash(password) if self.role is None: if self.email == current_app.config['COSTAPP_ADMIN']: self.role = Role.query.filter_by(name='Administrator').first() if self.role is None: self.role = Role.query.filter_by(default=True).first() def check_password(self, password): return check_password_hash(self.password_hash, password) def can(self, permissions): return self.role.permissions is not None and\ (self.role.permissions & permissions) == permissions def is_administrator(self): return self.can(Permission.ADMIN) def __repr__(self): return f"Name = {self.username} " def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}) def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.commit() return True def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}) def to_json(self): user_json = { 'url': url_for('api.get_user', id=self.id, _external=True), 'username': self.username, 'role': self.role.name, 'groups': url_for('api.get_user_groups', id=self.id, _external=True) } return user_json def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}).decode('ascii') @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return None return User.query.get(data['id']) @staticmethod def from_json(user_json): username = user_json.get('username') email = user_json.get('email') password_hash = generate_password_hash(user_json.get('password')) return User(username, email, password_hash)
class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(32), index=True, unique=True) password_hash = db.Column(db.String(128)) company = db.Column(db.String(64)) email = db.Column(db.String(32)) access_token = db.Column(db.String(128), index=True, unique=True) available_services = db.relationship('Service', secondary=access_table, lazy='dynamic', backref=db.backref('users', lazy='dynamic')) @property def other_services(self): ids = [item.id for item in self.available_services] return Service.query.filter(~Service.id.in_(ids)) 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) @staticmethod def _validate(data): errors = [] if ' ' in (data.get('username') or ' '): errors.append( "Имя пользователя должно быть не пустым, и не должно содержать пробелы" ) if User.query.filter_by(username=data.get('username')).count() != 0: errors.append("К сожалению данный логин уже занят") if ' ' in (data.get('password') or ' '): errors.append("Пароль не должен содержать пробелы") if len(data.get('company', '')) == 0: errors.append("Название компании не может быть пустым") if User.query.filter_by(email=data.get('email')).count() != 0: errors.append("Аккаунт с этой почтой уже зарегестрирован") return not bool(errors), errors def to_dict(self, full=False): data = { 'username': self.username, 'company': self.company, 'email': self.email, 'access_token': self.access_token } return data def _from_dict(self, data): for field in ['username', 'company', 'email']: if field in data: setattr(self, field, data[field]) if 'password' in data: self.set_password(data['password']) @staticmethod def register(data): flag, errors = User._validate(data) if flag: new_user = User() new_user._from_dict(data) token = token_urlsafe(60) while User.query.filter_by(access_token=token).count() > 0: token = token_urlsafe(60) new_user.access_token = token db.session.add(new_user) db.session.commit() return new_user, None return None, errors
class ArchiveCS(db.Model, CRUDMixin): __tablename__ = 'archive_employees' id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(100), unique=False, index=True) last_name = db.Column(db.String(100), unique=False, index=True) middle_name = db.Column(db.String(100), unique=False, index=True) pos_plan = db.Column(db.Integer, nullable=False) pos_fact = db.Column(db.Integer, nullable=False) nps_plan = db.Column(db.Float, nullable=False) nps_fact = db.Column(db.Float, nullable=False) refund_fz = db.Column(db.Boolean, nullable=False) fz_plan = db.Column(db.Float, nullable=False) fz_fact = db.Column(db.Float, nullable=False) sms_plan = db.Column(db.Float, nullable=False) sms_fact = db.Column(db.Float, nullable=False) kr_plan = db.Column(db.Integer, nullable=False) kr_fact = db.Column(db.Integer, nullable=False) box_plan = db.Column(db.Integer, nullable=False) box_fact = db.Column(db.Integer, nullable=False) ops_plan = db.Column(db.Integer, nullable=False) ops_fact = db.Column(db.Integer, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='cascade'), nullable=False) rating_id = db.relationship('Rating', secondary='association', back_populates='employees', cascade="all,delete") @property def pos_ratio(self): if self.pos_plan == 0: return 100 else: return round(100 * self.pos_fact / self.pos_plan, 2) @property def nps_ratio(self): if self.nps_plan == 0: return 100 else: return round(100 * self.nps_fact / self.nps_plan, 2) @property def refund_fz_ratio(self): if self.refund_fz is False: return 100 else: return 0 @property def fz_ratio(self): if self.fz_plan == 0: return 100 else: return round(100 * self.fz_fact / self.fz_plan, 2) @property def sms_ratio(self): if self.sms_plan == 0: return 100 else: return round(100 * self.sms_fact / self.sms_plan, 2) @property def kr_ratio(self): if self.kr_plan == 0: return 100 else: return round(100 * self.kr_fact / self.kr_plan, 2) @property def box_ratio(self): if self.box_plan == 0: return 100 else: return round(100 * self.box_fact / self.box_plan, 2) @property def ops_ratio(self): if self.ops_plan == 0: return 100 else: return round(100 * self.ops_fact / self.ops_plan, 2) @property def fio(self): return f'{self.last_name} {self.first_name} {self.middle_name}' def __repr__(self): return f'{self.last_name} {self.first_name} {self.middle_name}' def pretty_format(self, num): locale.setlocale(locale.LC_ALL, '') locale._override_localeconv = {'mon_thousands_sep': ' '} return locale.format('%.0f', num, grouping=True) def total_ratio(self, **kwargs): pos_weight = kwargs.get('pos_weight') nps_weight = kwargs.get('nps_weight') fz_weight = kwargs.get('fz_weight') refund_fz_weight = kwargs.get('refund_fz_weight') sms_weight = kwargs.get('sms_weight') kr_weight = kwargs.get('kr_weight') box_weight = kwargs.get('box_weight') ops_weight = kwargs.get('ops_weight') ratio = self.pos_ratio*pos_weight+self.nps_ratio*nps_weight+\ self.fz_ratio*fz_weight+self.refund_fz_ratio*refund_fz_weight+\ self.sms_ratio*sms_weight+self.kr_ratio*kr_weight+\ self.box_ratio*box_weight+self.ops_ratio*ops_weight ratio = round(ratio / 100, 2) return ratio