class Users(db.Model): """System user model.""" __tablename__ = 'users' # __table_args__ = {'schema': 'innerInformationSystem_System'} id = db.Column(db.Integer, primary_key=True, comment="Уникальный идентификатор") login = db.Column(db.String(20), unique=True, comment="Уникальный логин") photo = db.Column(db.String(50), comment="Имя файла фотокарточки") name = db.Column(db.String(20), comment="Имя") surname = db.Column(db.String(20), comment="Фамилия") patronymic = db.Column(db.String(20), comment="Отчество") phone = db.Column(db.String(13), unique=True, comment="Телефон") about_me = db.Column(db.Text(), comment="О себе (например, должность)") birth_date = db.Column(db.Date, comment="Дата рождения") employment_date = db.Column(db.Date, comment="Дата трудоустройства") status = db.Column(db.Boolean, default=False, nullable=False, comment="Статус записи пользователя") modules = db.relationship('Modules', secondary=user_module, lazy='subquery', backref=db.backref('users', lazy=True)) structures = db.relationship('OrganizationalStructure', secondary=user_structure, lazy='subquery', backref=db.backref('users', lazy=True)) emails = db.relationship('Emails', backref='users', lazy='dynamic') passwords = db.relationship('Passwords', backref='users', lazy='dynamic') # def __init__(self, login, password, # name, surname, patronymic, # email, phone, birth_date, about_me=None, # last_login=None, status=None, socials=None, photo=None): # """Конструктор класса.""" # self.login = login # self.password = { # "value": bcrypt.generate_password_hash(password).decode('utf-8'), # "blocked": False, # "first_auth": True, # "activeUntil": (datetime.now() + relativedelta( # months=1)).isoformat(), # "failed_times": 0 # } # self.socials = {"ok": "", # "vk": "", # "google": "", # "yandex": ""} if socials is None else socials # self.photo = None if photo is None else photo # self.name = name # self.surname = surname # self.patronymic = patronymic # self.email = cms_user_emails(email) # self.phone = phone # self.birth_date = birth_date # self.last_login = None if last_login is None else last_login # self.status = 1 if status is None else status # self.about_me = '' if about_me is None else about_me def __repr__(self): """Class representation string.""" return 'User with login: %r ' % (self.login)
class ChangeLogMixin(object): operation = db.Column(db.Text())
class User(UserMixin, Model, SurrogatePK): __tablename__ = 'users' email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) avatar_hash = db.Column(db.String(32)) posts = db.relationship('Post', backref='author', lazy='dynamic') followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') comments = db.relationship('Comment', backref='author', lazy='dynamic') @staticmethod def add_self_follows(): for user in User.query.all(): if not user.is_following(user): user.follow(user) db.session.add(user) db.session.commit() def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['ADMIN']: self.role = Role.query.filter_by(name='Administrator').first() if self.role is None: self.role = Role.query.filter_by(default=True).first() if self.email is not None and self.avatar_hash is None: self.avatar_hash = self.gravatar_hash() self.follow(self) @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) def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}).decode('utf-8') def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.add(self) return True def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}).decode('utf-8') @staticmethod def reset_password(token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False user = User.query.get(data.get('reset')) if user is None: return False user.password = new_password db.session.add(user) return True def generate_email_change_token(self, new_email, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({ 'change_email': self.id, 'new_email': new_email }).decode('utf-8') def change_email(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False if data.get('change_email') != self.id: return False new_email = data.get('new_email') if new_email is None: return False if self.query.filter_by(email=new_email).first() is not None: return False self.email = new_email self.avatar_hash = self.gravatar_hash() db.session.add(self) return True def can(self, perm): return self.role is not None and self.role.has_permission(perm) def is_administrator(self): return self.can(Permission.ADMIN) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) def gravatar_hash(self): return hashlib.md5(self.email.lower().encode('utf-8')).hexdigest() def gravatar(self, size=100, default='identicon', rating='g'): url = 'https://secure.gravatar.com/avatar' hash = self.avatar_hash or self.gravatar_hash() return '{url}/{hash}?s={size}&d={default}&r={rating}'.format( url=url, hash=hash, size=size, default=default, rating=rating) def follow(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self, user): if user.id is None: return False return self.followed.filter_by(followed_id=user.id).first() is not None def is_followed_by(self, user): if user.id is None: return False return self.followers.filter_by( follower_id=user.id).first() is not None @property def followed_posts(self): return Post.query.join(Follow, Follow.followed_id == Post.author_id) \ .filter(Follow.follower_id == self.id) def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}).decode('utf-8') @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']) @classmethod def get_by_username(cls, username): return cls.query.filter_by(username=username).first() def __repr__(self): return '<User %r>' % self.username
class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer(), primary_key=True) title = db.Column(db.String(255), nullable=False) content = db.Column(db.Text(), nullable=False) user_id = db.Column(db.Integer(), db.ForeignKey('users.id'), nullable=False) category_id = db.Column(db.Integer(), db.ForeignKey('categories.id'), nullable=False) comments = db.relationship('Comment', backref='post', lazy='dynamic') posted_at = db.Column( db.TIMESTAMP, nullable=False, default=datetime.now(tz=pytz.timezone("Europe/Stockholm")), ) def __repr__(self): return '<Post %r>' % self.id @classmethod def create(cls, title, post_content, user_id, category_id): """ Create a new post Args: title: the post title post_content: post content user_id: the user who posted it category_id: what category the post is in Returns: A newly created post """ post = cls(title=title, content=post_content, user_id=user_id, category_id=category_id) db.session.add(post) db.session.commit() return post @classmethod def get_by_comment(cls, post_id, comment_id): """ Get comment by post and comment id Args: post_id: post id comment_id: comment id Returns: The first comment matched by post_id and comment_id """ return cls.get_by_id(post_id).comments.filter_by(id=comment_id).first_or_404() @classmethod def all(cls): """ Get all posts Returns: A list of posts """ return cls.query.all() @classmethod def paginate(cls, page=1, per_page=5): """ Paginate through all posts Args: page: current page per_page: how many items displayed per page Returns: A paginated object """ return cls.query.order_by(cls.posted_at.desc()).paginate(page, per_page, False) @classmethod def get_by_id(cls, post_id): """ Get a post by id Args: post_id: specified post id Returns: The first post that matches by id """ return cls.query.filter_by(id=post_id).first_or_404() @classmethod def get_recent_posts(cls, limit=5): """ Get all latest posts with a limit Args: limit: the limit of results to be displayed Returns: A list of posts with the specified limit """ return cls.query.order_by(cls.posted_at.desc()).limit(limit).all() @classmethod def search(cls, query, page, per_page): """ Get all posts matching the search query Args: page: current page per_page: results per page query: specified query for searching Returns: A list of posts that match the search query """ return cls.query.filter(cls.title.like('%{0}%'.format(query))).paginate(page, per_page, True) @classmethod def delete_by_id(cls, post_id, user_id): """ Delete a post by id Args: user_id: the current logged in user post_id: the post to be deleted Returns: boolean """ post = cls.get_by_id(post_id) if post.user.id == user_id: for comment in post.comments: db.session.delete(comment) db.session.delete(cls.get_by_id(post_id)) db.session.commit() return True else: return False def paginate_comments(self, page, per_page): """ Paginate through a post's comments Args: page: current page per_page: amount of results per page Returns: A paginated object of comments """ return self.comments.paginate(page, per_page) def update(self, title, content, category_id): """ Update a post and its values Args: title: new title content: new content category_id: a new category Returns: void """ self.title = title self.content = content self.category_id = category_id db.session.commit() def to_dict(self): """ Create a dictionary with table columns Returns: dict """ return dict(title=self.title, content=self.content, posted_at=self.posted_at)
class Group(db.Model, AbstractBaseGroup): """ Group model class. """ id = db.Column(db.Integer(), primary_key=True, autoincrement=True) name = db.Column(db.String(32), unique=True) users = many_to_many("Group", "User", backref_name="groups") introduction = db.Column(db.Text())
class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) password_hash = db.Column(db.String(128)) email = db.Column(db.String(64), unique=True, index=True) confirmed = db.Column(db.Boolean, default=False) name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) avatar_hash = db.Column(db.String(32)) posts = db.relationship('Post', backref='author', lazy='dynamic') followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') comments = db.relationship('Comment', backref='author', lazy='dynamic') def follow(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self,user): return self.followed.filter_by(followed_id=user.id).first() is not None def is_followed_by(self, user): return self.followers.filter_by(follower_id=user.id).first() is not None @staticmethod def generate_fake(count=100): from sqlalchemy.exc import IntegrityError from random import seed import forgery_py seed() for i in range(count): u = User(email=forgery_py.internet.email_address(), username=forgery_py.internet.user_name(True), password=forgery_py.lorem_ipsum.word(), confirmed=True, name=forgery_py.name.full_name(), location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentence(), member_since=forgery_py.date.date(True)) db.session.add(u) try: db.session.commit() except IntegrityError: db.session.rollback() def gravatar(self, size=100, default='identicon', rating='g'): if request.is_secure: url = 'https://securer.gravatar.com/avatar' else: url = 'http://www.gravatar.com/avatar' hash = self.avatar_hash or hashlib.md5( self.email.encode('utf-8')).hexdigest() return '{url}/{hash}?s={size}&d={default}&r={rating}'.format( url=url, hash=hash, size=size, default=default, rating=rating ) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}) def generate_reset_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.add(self) return True def can(self, permissions): return self.role is not None and \ (self.role.permissions and permissions) == permissions def is_administrator(self): return self.can(Permission.ADMINISTER) @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) def reset_password(self, token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('confirm') != self.id: return False self.password = new_password db.session.add(self) return True def generate_email_change_token(self, new_email, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'change_email':self.id, 'new_email': new_email}) def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['FLASKY_ADMIN']: self.role = Role.query.filter_by(permissions=0xff).first() if self.role is None: self.role = Role.query.filter_by(default=True).first() if self.email is not None and self.avatar_hash is None: self.avatar_hash = hashlib.md5( self.email.encode('utf-8')).hexdigest() def change_email(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('change_email') != self.id: return False new_email = data.get('new_email') if new_email is None: return False if self.query.filter_by(email=new_email).first() is not None: return False self.email = new_email self.avatar_hash = hashlib.md5( self.email.encode('utf-8')).hexdigest() db.session.add(self) return True @staticmethod def add_self_follow(): for user in User.query.all(): if not user.is_following(user): user.follow(user) db.session.add(user) db.session.commit() @property def followed_posts(self): return Post.query.join(Follow, Follow.followed_id == Post.author_id)\ .filter(Follow.follower_id == self.id) def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}) @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']) def to_json(self): json_user = { 'url': url_for('api.get_post', id=self.id, _external=True), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen, 'posts': url_for('api.get_user_followed_posts', id=self.id, _external=True), 'post_count': self.posts.count() } return json_user def __repr__(self): return '<User %r>' % self.username
class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True, unique=True) name = db.Column(db.String(120), index=True) birthdate = db.Column(db.DateTime) gender = db.Column(db.String, default="Unknown") location = db.Column(db.String(120)) latitude = db.Column(db.Float) longitude = db.Column(db.Float) sin_rad_lat = db.Column(db.Float) cos_rad_lat = db.Column(db.Float) rad_lng = db.Column(db.Float) username = db.Column(db.String(120), index=True, unique=True) email = db.Column(db.String(120), index=True) password_hash = db.Column(db.String(128)) profile_pic_id = db.Column(db.Integer, db.ForeignKey('picture.id')) profile_pic = db.relationship("Picture", foreign_keys=[profile_pic_id]) cover_pic_id = db.Column(db.Integer, db.ForeignKey('picture.id')) cover_pic = db.relationship("Picture", foreign_keys=[cover_pic_id]) def __init__(self, **kwargs): super(User, self).__init__(**kwargs) # do custom initialization here self.profile_pic = Picture( path=f"/static/images/profiles/{self.username}/profile_pic", replacement=gravatar(self.email.lower())) self.cover_pic = Picture( path=f"/static/images/profiles/{self.username}/cover_pic", replacement="/static/images/defaults/world.jpg") befriended = db.relationship( 'User', secondary=befriends, primaryjoin=(befriends.c.befriend_id == id), secondaryjoin=(befriends.c.befriended_id == id), backref=db.backref('befriends', lazy='dynamic'), lazy='dynamic') memberships = db.relationship('Membership', backref='owner', lazy='dynamic', foreign_keys='Membership.owner_id') bio = db.Column(db.Text()) def befriend(self, profile): if not self.is_befriending(profile): self.befriended.append(profile) def abolish_befriending(self, profile): if self.is_befriending(profile): self.befriended.remove(profile) @hybrid_method def is_befriending(self, profile): return User.query.filter(User.id == profile.id).filter( User.befriends.any(id=self.id)).count() > 0 @hybrid_method def is_connected_to(self, profile): return self.is_befriending(profile) and profile.is_befriending(self) def form_connection_with(self, profile): if not self.is_befriending(profile): self.befriend(profile) if not profile.is_befriending(self): profile.befriend(self) @hybrid_property def connections(self): return User.query.filter(User.befriends.any(id=self.id)).filter( befriends.c.befriended_id == User.id) def get_connections_from_text(self, text, already_chosen=None): query = self.connections.filter( func.lower(User.name).like(f'%{text.lower()}%')) if already_chosen: for username in already_chosen: query = query.filter(User.username != username) return query def get_received_messages_from(self, profile): return self.received_messages.filter_by(sender=profile) def get_sent_messages_to(self, profile): return self.sent_messages.filter_by(recipient=profile) def get_messages_with(self, profile): return self.get_received_messages_from(profile).union( self.get_sent_messages_to(profile)) def has_skill(self, title): return any([skill.title == title for skill in self.skills.all()]) def has_skills(self, titles): return all([title in self.skill_titles for title in titles]) @hybrid_property def skill_titles(self): return [skill.title for skill in self.skills.all()] def set_birthdate(self, date): self.birthdate = date # Submitted applications: submitted_applications = db.relationship( 'Application', backref='sender', lazy='dynamic', foreign_keys='Application.sender_id') # Received applications: received_applications = db.relationship( 'Application', backref='recipient', lazy='dynamic', foreign_keys='Application.recipient_id') sent_messages = db.relationship('Message', backref='sender', lazy='dynamic', foreign_keys='Message.sender_id') received_messages = db.relationship('Message', backref='recipient', lazy='dynamic', foreign_keys='Message.recipient_id') skills = db.relationship('Skill', backref='owner', lazy='dynamic', foreign_keys='Skill.owner_id') 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 set_location(self, location, prelocated=False): if not prelocated: location = geocode(location) if location: self.location = location.address self.latitude = location.latitude self.longitude = location.longitude self.sin_rad_lat = math.sin(math.pi * location.latitude / 180) self.cos_rad_lat = math.cos(math.pi * location.latitude / 180) self.rad_lng = math.pi * location.longitude / 180 return location @hybrid_property def age(self): return get_age(self.birthdate) @hybrid_method def is_older_than(self, age): return is_older(self.birthdate, age) @hybrid_method def is_younger_than(self, age): return is_younger(self.birthdate, age) @hybrid_method def is_nearby(self, latitude, longitude, radius): sin_rad_lat = math.sin(math.pi * latitude / 180) cos_rad_lat = math.cos(math.pi * latitude / 180) rad_lng = math.pi * longitude / 180 return func.acos(self.cos_rad_lat * cos_rad_lat * func.cos(self.rad_lng - rad_lng) + self.sin_rad_lat * sin_rad_lat) * 6371 <= radius def __repr__(self): return '<User {}>'.format(self.username)
class User(UserMixin, db.Model): ''' user class is a table for attribute of users info id - username - email - password_hash - posts - about_me - last_seen - get_reset_password_token - method verify_reset_password_token - method followed_posts - method follow unfollow is_following avatar - method check_password - method ''' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(255), unique=True) about_me = db.Column(db.Text(1024)) email = db.Column(db.String(255)) email_confirmed = db.Column(db.Integer, default = 0) expire_date_request_confirm_password = db.Column(db.DateTime, default=main_utils.min_date_for_calculation()) expire_date_request_bufer_mail = db.Column(db.DateTime, default=main_utils.min_date_for_calculation()) bufer_email = db.Column(db.String(120)) #дата регистрации пользователя registration_date = db.Column(db.DateTime, default=datetime.utcnow) #поле которое говорит о том зарегистрирован пользователь мастером или же #самостоятельно через почту или телефон по умолчанию = 0 user_from_master = db.Column(db.Integer, default=0) #максимальное количество попыток зарегистрировать новый телефоны trying_to_enter_new_phone = db.Column(db.Integer, default=15) password_hash = db.Column(db.String(128)) #юзеры и админы role = db.Column(db.String(10), index=True); last_seen = db.Column(db.DateTime, default=datetime.utcnow) #типы связи с клиентом connection_type_id = db.Column(db.Integer, db.ForeignKey('connection_type.id')) #телефоны клиента phones = db.relationship('UserPhones', backref='user', lazy='dynamic') #электронные аккаунты клиента internet_accaunts = db.relationship('UserInternetAccount', backref='user', lazy='dynamic') #обратная ссылка из таблицы расписания для связи зарегистрированного пользователя и времени записи на прием # date_of_schedules = db.relationship('ScheduleOfDay', backref='user', lazy='dynamic') posts = db.relationship('Post', backref='author', lazy='dynamic') master_profile = db.relationship('NailMaster', backref='user', uselist=False) 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 has_phone(self): ''' функция возвращает правду если у пользователя есть хотябы один подтвержденный телефон ''' return UserPhones.query.filter(UserPhones.user_id == self.id).filter(UserPhones.phone_checked == 1).all().count() > 0 def set_confirm_email_true(self): ''' func change in db status email from not confirm to confirm by create new pass ''' if self.email_confirmed != 1: self.email_confirmed = 1 def set_password(self, password): ''' func to generate hash pass for save in db ''' self.password_hash = generate_password_hash(password) def check_password(self, password): ''' func chech hash pass from bd with secret key and resume tru or false ''' return check_password_hash(self.password_hash, password) def avatar(self, size): ''' func return aatar from srvice Gravatar ''' digest = None if not self.email or self.email == "": digest = "*****@*****.**" else: 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): ''' func for subscribe to see oa activety user ''' if not self.is_following(user): self.followed.append(user) def unfollow(self, user): ''' func for unsubscribe to see oa activety user ''' if self.is_following(user): self.followed.remove(user) def is_following(self, user): ''' func for check that user not folowed twice on one user ''' return self.followed.filter( followers.c.followed_id == user.id).count() > 0 def followed_posts(self): ''' func to order post by users ''' 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()) def get_new_registration_token(self, expires_in=600): ''' func to create token link for request registration new user. time of life 10min for default ''' return jwt.encode( {'register_user': self.id, 'exp': time() + expires_in}, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8') @staticmethod def verify_new_registration_token(token): ''' func to decode token from link to registartion new user ''' try: id = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])['register_user'] except: return return User.query.get(id) def get_reset_password_token(self, expires_in=600): ''' func to create token link for request reset password. time of life 10min for default ''' return jwt.encode( {'reset_password': self.id, 'exp': time() + expires_in}, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8') @property def is_admin(self): ''' property of user - return true ifuser is Administrator group ''' return self.role == 'admin' @staticmethod def verify_reset_password_token(token): ''' func to decode token from link to reset pass ''' try: id = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password'] except: return return User.query.get(id)
class NutemProject(db.Model): """Represents Proected users.""" '''Table: nutem_project Columns: id varchar(32) PK createTime datetime deleted bit(1) lastEditTime datetime lastEditor varchar(255) uniqueId varchar(255) buildTime varchar(20) compactStatus varchar(40) customerName varchar(100) feeAmount varchar(20) finalCustomerName varchar(100) operateTime varchar(20) projectStatus varchar(255) sn varchar(50) summary varchar(250) teamwork varchar(200) techName varchar(50) title varchar(100) titleEn varchar(100) manager_id varchar(32) multi_project_id varchar(32) monitor varchar(32) coding varchar(20) workflowStatus varchar(255) qulityFiles longtext taskFile varchar(255)''' # Set the name for table __tablename__ = 'nutem_project' id = db.Column(db.String(32), primary_key=True, unique=True) createTime = db.Column(db.DateTime()) deleted = db.Column(db.Boolean()) lastEditTime = db.Column(db.DateTime()) lastEditor = db.Column(db.String(255)) uniqueId = db.Column(db.String(255)) buildTime = db.Column(db.String(20)) compactStatus = db.Column(db.String(40)) customerName = db.Column(db.String(100)) feeAmount = db.Column(db.String(20)) finalCustomerName = db.Column(db.String(100)) operateTime = db.Column(db.String(20)) projectStatus = db.Column(db.String(255)) sn = db.Column(db.String(50)) summary = db.Column(db.String(250)) teamwork = db.Column(db.String(200)) techName = db.Column(db.String(50)) title = db.Column(db.String(100)) titleEn = db.Column(db.String(20)) manager_id = db.Column(db.String(32)) multi_project_id = db.Column(db.String(32)) monitor = db.Column(db.String(32)) coding = db.Column(db.String(20)) workflowStatus = db.Column(db.String(255)) qulityFiles = db.Column(db.Text()) taskFile = db.Column(db.String(255)) def __init__(self, id, createTime, deleted, lastEditTime, lastEditor, uniqueId, buildTime, compactStatus, customerName, feeAmount, finalCustomerName, operateTime, projectStatus\ , sn, summary, teamwork, techName, title, titleEn, manager_id, multi_project_id, monitor, coding, workflowStatus, qulityFiles, taskFile): self.id = id self.createTime = createTime self.deleted = deleted self.lastEditTime = lastEditTime self.lastEditor = lastEditor self.uniqueId = uniqueId self.buildTime = buildTime self.compactStatus = compactStatus self.customerName = customerName self.feeAmount = feeAmount self.finalCustomerName = finalCustomerName self.operateTime = operateTime self.projectStatus = projectStatus self.sn = sn self.summary = summary self.teamwork = teamwork self.techName = techName self.title = title self.titleEn = titleEn self.manager_id = manager_id self.multi_project_id = multi_project_id self.monitor = monitor self.coding = coding self.workflowStatus = workflowStatus self.qulityFiles = qulityFiles self.taskFile = taskFile def __repr__(self): #__repr__ 当打印User对象时显示的数据。 return "<Model NutemProject `{}`>".format(self.id)
class Task(db.Model): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), nullable=False) about = db.Column(db.Text(), nullable=False) codes = db.relationship('Code', backref='task', lazy=True)
class FlickrAccount(Account): key = db.Column(db.Text(convert_unicode=True)) secret = db.Column(db.Text(convert_unicode=True)) oauth_token = db.Column(db.Text(convert_unicode=True)) oauth_secret = db.Column(db.String)
class Test(db.Model): id = db.Column(db.Integer(), primary_key=True) id_code = db.Column(db.Integer(), db.ForeignKey('code.id')) input_data = db.Column(db.Text(), nullable=False) output_data = db.Column(db.Text(), nullable=False)
class User(UserMixin, db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(128)) role_id = db.Column(db.Integer, db.ForeignKey("roles.id")) name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) avatar_hash = db.Column(db.String(32)) posts = db.relationship("Post", backref="author", lazy="dynamic") followed = db.relationship("Follow", foreign_keys=[Follow.follower_id], backref=db.backref("follower", lazy="joined"), lazy="dynamic", cascade="all, delete-orphan") followers = db.relationship("Follow", foreign_keys=[Follow.followed_id], backref=db.backref("followed", lazy="joined"), cascade="all, delete-orphan") comments = db.relationship("Comment", backref="author", lazy="dynamic") @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) @property def followed_posts(self): return Post.query.join(Follow, Follow.followed_id == Post.author_id)\ .filter(Follow.follower_id == self.id) def verify_password(self, password): return check_password_hash(self.password_hash, password) def can(self, permissions): return self.role is not None and \ (self.role.permissions & permissions) == permissions def is_administrator(self): return self.can(Permission.ADMINISTER) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) def follow(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self, user): return self.followed.filter_by(followed_id=user.id).first() is not None def is_followed_by(self, user): return self.followers.filter_by( follower_id=user.id).first() is not None # def gravatar(self, size=100, default="identicon", rating="g"): # if request.is_secure: # url = "https://secure.gravatar.com/avatar" # else: # url = "http://www.gravatar.com/avatar" # hash = self.avatar_hash or hashlib.md5( # self.email.encode("utf-8")).hexdigest() # return "{url}/{hash}?s={size}&d={default}&r={rating}".format( # url=url, hash=hash, size=size, default=default, rating=rating) @staticmethod def generate_fake(count=100): from sqlalchemy.exc import IntegrityError from random import seed import forgery_py seed() for i in range(count): u = User(email=forgery_py.internet.email_address(), username=forgery_py.internet.user_name(True), password=forgery_py.lorem_ipsum.word(), name=forgery_py.name.full_name(), location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentence(), member_since=forgery_py.date.date(True)) db.session.add(u) try: db.session.commit() except IntegrityError: db.session.rollback() @staticmethod def add_self_follows(): for user in User.query.all(): if not user.is_following(user): user.follow(user) db.session.add(user) db.session.commit() def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config["FLASKY_ADMIN"]: self.role = Role.query.filter_by(permissions=0xff).first() if self.role is None: self.role = Role.query.filter_by(default=True).first() if self.email is not None and self.avatar_hash is None: self.avatar_hash = hashlib.md5( self.email.encode("utf-8")).hexdigest() self.follow(self) def __repr__(self): return "<User {0}>".format(self.username)
class User(db.Model, UserMixin): """ User模型 """ __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, index=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(128)) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) real_name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text(512)) avatar = db.Column(db.String(128), default='avatar.jpg') member_since = db.Column(db.DateTime(), default=datetime.utcnow) posts = db.relationship('Post', backref='author', lazy='dynamic') followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') comments = db.relationship('Comment', backref='author', lazy='dynamic') def __init__(self, **kwargs): """ :summary: User模型初始化函数,生成用户时自动赋予角色,创建用户的数据文件夹,super()函数继承父类, :param kwargs: """ super(User, self).__init__(**kwargs) if self.role is None: self.role = Role.query.filter_by(default=True).first() # 设置password的可写不可读 @property def password(self): raise AttributeError('密码是一个不可读的属性') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) # 验证密码 def verify_password(self, password): """ :summary: 验证密码 :param password: :return: """ return check_password_hash(self.password_hash, password) def generate_reset_token(self, expiration=3600): """ :summary: 生成重设密码的token :param expiration: token失效时间,单位为秒 :return: """ s = TimedJSONWebSignatureSerializer( secret_key=current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'reset_password': self.id}) def reset_password(self, token, new_password): """ :summary: 验证token并重设密码 :param token: :param new_password: :return: """ s = TimedJSONWebSignatureSerializer( secret_key=current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('reset_password') != self.id: return False self.password = new_password db.session.add(self) return True def can(self, permissions): """ :summary: 检查用户是否具有指定的权限,使用位与操作来实现 :param permissions: :return: """ return self.role is not None and (self.role.permissions & permissions) == permissions def is_administrator(self): """ :summary: 检查管理员权限的功能经常用到,因此使用单独的方法 is_administrator() 实现 :return: """ return self.can(Permission.ADMINISTER) @staticmethod def create_fake(count=100): """ :summary: 创建虚假的用户数据 :param count: 数量 :return: """ from random import seed import forgery_py from sqlalchemy.exc import IntegrityError seed() for i in range(count): u = User(email=forgery_py.internet.email_address(), username=forgery_py.internet.user_name(True), password=forgery_py.lorem_ipsum.word(), real_name=forgery_py.name.full_name(), location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentence(), member_since=forgery_py.date.date(True)) db.session.add(u) # 因为用户名和邮箱只能是唯一的,而随机生成的数据可能会重复 # 因此在数据库提交的时候会引发IntegrityError错误使得程序停止运行 # 这里使用try来捕获这个异常并且回滚数据库操作,就能保证正常运行 try: db.session.commit() except IntegrityError: db.session.rollback() @staticmethod def add_self_follows(): """ :summary: 让用户把自己设置为关注者 :return: """ for u in User.query.all(): if not u.is_following(u): u.follow(u) db.session.add(u) db.session.commit() def follow(self, user): """ :summary: 关注一个用户 :param user: :return: """ if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): """ :summary: 取消关注一个用户 :param user: :return: """ f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self, user): """ :summary: 判断是否正在关注某个用户 :param user: :return: """ f = self.followed.filter_by(followed_id=user.id).first() return f is not None def is_followed_by(self, user): """ :summary: 判断是否被某个用户关注 :param user: :return: """ f = self.followers.filter_by(follower_id=user.id).first() return f is not None @property def followed_posts(self): """ :summary: 获取所关注用户的微博,使用@property装饰器将该方法定义为属性,则在调用时候就可以不用加() :return: """ return Post.query.join(Follow, Follow.followed_id == Post.author_id).filter( Follow.follower_id == self.id)
class Agenda(db.Model): id = db.Column(db.Integer, primary_key=True) date = db.Column(db.String(10)) name_event = db.Column(db.String(64)) local = db.Column(db.String(64)) description = db.Column(db.Text())
class Data(db.Model): __tablename__ = 'updated_data' __searchable__ = ['NumberSI', 'NameSI', 'DesignationSI', 'ManufacturerSI'] ids = db.Column(db.Integer, primary_key=True) dates = db.Column(db.DateTime, default=datetime.now()) # Дата записи в базу date = db.Column(db.String(255)) # дата опубликования NameSI = db.Column(db.Text()) # Наименование СИ NumberSI = db.Column(db.String(255)) # Номер госреестра MPISI = db.Column(db.String(600)) # Межповерочный интервал МПИ CertificateLifeSI = db.Column(db.String(255)) # Срок свидетельства DesignationSI = db.Column(db.Text()) # Обозначение типа СИ YearSI = db.Column(db.Integer()) # Лет ManufacturerTotalSI = db.Column(db.Text()) # Изготовитель средства измерения CountrySI = db.Column(db.String(255)) # Страна SettlementSI = db.Column(db.String(255)) # Населенный пункт ManufacturerSI = db.Column(db.Text()) # Предприятие-изготовитель DescriptionSI = db.Column(db.String(255)) # Описание типа ссылка MethodVerifSI = db.Column(db.String(255)) # Методики поверки ссылка DescriptionSiName = db.Column(db.String(255)) # Описание типа имя файла MethodVerifSiName = db.Column(db.String(255)) # Методики поверки имя файла FactoryNumSI = db.Column(db.Text()) # Заводской номер id = db.Column(db.Integer()) # ID # name_device = db.Column(db.String(255)) # наименование прибора ( манометры, напоромеры, дифманометры ) Maker = db.Column(db.Text()) # Сгенерированный ManufacturerTotalSI Slug = db.Column(db.Text()) # Сгенерированный NameSI + id def __init__(self, *args, **wkargs): super(Data, self).__init__(*args, **wkargs) def __repr__(self): return f'{self.ids} | {self.ManufacturerTotalSI} | {self.MethodVerifSI} | {self.DescriptionSI}' # ================================================== методы модели ===================================================== # получить кольичетво производителей def get_count(self, value): return db.session.query(func.count(Data.Maker)).filter(Data.Maker == value).scalar() # получаем из ссылки id def get_id_from_link(self, link): if link: return link.rsplit('-', 1)[-1] # создаем ссылку def create_link(self): if self.NameSI: return f'{slugify(self.NameSI)}-{self.ids}' return f'{self.NumberSI}-{self.ids}' # шаблон для реализации вывода подсветки поиска def repl(self, match): return f'<mark>{match[0]}</mark>' # выборка из поиска найденного значения def rex_select_row(self, text, value): if value is not None and value != '': return re.sub(fr'{value.split()[0]}\s*([А-Яа-яЁёA-Za-z0-9]*)', self.repl, text, flags=re.IGNORECASE) return text
class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=True) location = db.Column(db.String(64)) name = db.Column(db.String(64)) member_since = db.Column(db.DateTime(), default=datetime.utcnow) about_me = db.Column(db.Text()) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) password_hash = db.Column(db.String(128)) posts = db.relationship('Post', backref='author', lazy='dynamic') followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: self.role = Role.query.filter_by(default=True).first() def __repr__(self): return '<User %r>' % self.username @property def password(self): raise AttributeError('password is not readable') @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) def has_permission(self, perm): return self.role is not None and self.role.has_permission(perm) def is_administrator(self): return self.has_permission(Permission.ADMIN) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) def is_following(self, user): return self.followed.filter_by(followed_id=user.id).first() is not None def is_followed(self, user): return self.followers.filter_by( follower_id=user.id).first() is not None def follow(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) db.session.commit() def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) db.session.commit()
class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) #邮箱 username = db.Column(db.String(64), unique=True, index=True) #用户名 role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) #身份 password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) #是否认证 name = db.Column(db.String(64)) #真实姓名 location = db.Column(db.Text()) #所在地 about_me = db.Column(db.Text()) #自我介绍 member_since = db.Column(db.DateTime(), default=datetime.utcnow) #注册日期 #可以直接调用datetime.utcnow ,不加(),default可接受函数做默认值,需要生成默认值时,会自动调用指定函数 last_seen = db.Column(db.DateTime(), default=datetime.utcnow) #最后访问日期 avatar_hash = db.Column(db.String(32)) questions = db.relationship('Question', backref='author', lazy='dynamic') #在Question模型里面加了author属性,可通过author属性访问User模型,获取的是模型对象不是外键的值 answers = db.relationship('Answer', backref='author', lazy='dynamic') #在answers模型里面加了author属性,可通过author属性访问User模型,获取的是模型对象不是外键的值 comments = db.relationship('Comment', backref='author', lazy='dynamic') #在Comment模型里面加了author属性,可通过author属性访问User模型,获取的是模型对象不是外键的值 proves = db.relationship('Prove', backref='prover', lazy='dynamic') #在Prove属性里面添加了prover属性,可以通过prover获得 赞者的信息 followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') # followed代表当前用户所关注的用户,user.followed.all()返回已经关注的用户的列表 # backref 给Follow模型添加了follower属性。Follow模型可以用follower属性查找到当前用户,也就意味着Follow可通过follower(关注自己的用户,即粉丝)找到当前用户,被关注者可以通过 followed 找到关注者 # cascade "all, delete-orphan" to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated.删除对象将指向该纪录的实体也删除 followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') #代表关注用户本身的人,自己的粉丝,user.followers.all()返回自己的关注者的列表 #backref 给 Follow模型添加了followed属性。Follow模型可以用followed属性查找到当前用户,也就意味着Follow可通过followed(已关注的用户,即大v)找到当前用户,关注者可以通过 followed 找到被关注者 @staticmethod def generate_fake(count=100): from sqlalchemy.exc import IntegrityError from random import seed import forgery_py seed() for i in range(count): u = User( email=forgery_py.internet.email_address(), #forgery_py.forgery.internet.email_address(user=None) #Random e-mail address in a hopefully imaginary domain. #If user is None user_name() will be used. Otherwise it will be lowercased and will have spaces replaced with _. Domain name is created using domain_name(). username=forgery_py.internet.user_name(True), #forgery_py.forgery.internet.user_name(with_num=False): Random user name. #Basically it’s lowercased result of first_name() with a number appended if with_num. password=forgery_py.lorem_ipsum.word(), #forgery_py.forgery.lorem_ipsum.word(): Random word. confirmed=True, name=forgery_py.name.full_name(), #forgery_py.forgery.name.full_name():Random full name. Equivalent of first_name() + ' ' + last_name(). location=forgery_py.address.city(), # forgery_py.forgery.name.location():Random location name, e.g. MI6 Headquarters. # return random.choice(get_dictionary('locations')).strip(),从 about_me=forgery_py.lorem_ipsum.sentence(), #random sentence member_since=forgery_py.date.date(True)) #forgery_py.forgery.date.date(past=False, min_delta=0, max_delta=20)[source] #Random datetime.date object. Delta args are days. (if past:delta = delta * -1) db.session.add(u) try: db.session.commit() except IntegrityError: db.session.rollback() def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['FLASK_ADMIN']: self.role = Role.query.filter_by(permissions=0xff).first() if self.role is None: self.role = Role.query.filter_by(default=True).first() # 如果邮件地址和FLASKY_ADMIN中的邮箱相同,则成为Role中的Administrator if self.email is not None and self.avatar_hash is None: self.avatar_hash = hashlib.md5( self.email.encode('utf-8')).hexdigest() @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) 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) #data是个数组,{'confirm':self.id} except: return False if data.get('confirm' ) != self.id: #data.get('confirm')得到id,相等则匹配,confirm为True return False self.confirmed = True #confirmed属性设置为True db.session.add(self) 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 reset_password(self, token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('reset') != self.id: return False self.password = new_password db.session.add(self) db.session.commit() return True def generate_email_change_token(self, new_email, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'change_email': self.id, 'new_email': new_email}) def change_email(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('change_email') != self.id: return False new_email = data.get('new_email') if new_email is None: return False if self.query.filter_by(email=new_email).first() is not None: return False self.email = new_email self.avatar_hash = hashlib.md5(self.email.encode('utf-8')).hexdigest() db.session.add(self) db.session.commit() return True def can(self, permissions): #检查permissions权限是不是存在,在请求权限permissions和已赋予权限role.permissions之间进行位与操作 #位与操作返回存在的permissions,相等符合就返回True——所以如果存在该权限则返回True return self.role is not None and \ (self.role.permissions & permissions) == permissions def is_administrator(self): #检查管理员权限 return self.can(Permission.ADMINISTER) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) db.session.commit() def gravatar(self, size=128, default='identicon', rating='9'): # if request.is_secure: # url = 'https://secure.gravatar.com/avatar' # else: # url = 'https://www.gravatar.com/avatar' # hash = self.avatar_hash or hashlib.md5(self.email.encode('utf-8')).hexdigest() # return '{url}/{hash}?s={size}&d={default}&r={rating}'.format( # url=url, hash=hash, size=size, default=default, rating=rating # ) if request.is_secure: url = 'https://secure.gravatar.com/avatar/' else: url = 'https://www.gravatar.com/avatar/' hash = self.avatar_hash or hashlib.md5( self.email.encode('utf-8')).hexdigest() return url + hash + '?s=' + str(size) + '&d=' + str( default) + '&r=' + str(rating) def follow(self, user): if not self.is_following(user): #是否关注了这个user,如果没有,可以关注 f = Follow(follower=self, followed=user) #添加一个Follow模型对象,follwer和followed属性设立 db.session.add(f) db.session.commit() def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() #已经关注了该用户 if f: db.session.delete(f) db.session.commit() def is_following(self, user): #是否正在关注 return self.followed.filter_by(followed_id=user.id).first() is not None #user.followed.all/filter_by返回的是当前用户所关注的用户的的列表或者一部分列表 ,followed_id=user.id,代表查询的是当前用户是否关注这个id的用户 def is_followed_by(self, user): return self.followers.filter_by( follower_id=user.id).first() is not None #user.followers.filter def is_proving(self, answer_id): p = db.session.query(Prove).join( User, Prove.prover_id == User.id).filter( Prove.answer_id == answer_id).first() return p is not None @property def followed_questions(self): return Question.query.join( Follow, Follow.followed_id == Question.author_id).filter( Follow.follower_id == self.id) #获取所关注用户的提问 @property def self_questions(self): return Question.query.filter(Question.author_id == self.id) #获取自己的提问 def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}) @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']) #返回对应的用户 def __repr__(self): return '<User %r>' % self.username
class Group(db.Model): id = db.Column(db.Integer, primary_key=True) handle = db.Column(db.String(120), index=True, unique=True) name = db.Column(db.String(64)) description = db.Column(db.Text()) privacy = db.Column(db.String(7), default="Public") location_is_fixed = db.Column(db.Boolean, default=True) location = db.Column(db.String(120)) latitude = db.Column(db.Float) longitude = db.Column(db.Float) sin_rad_lat = db.Column(db.Float) cos_rad_lat = db.Column(db.Float) rad_lng = db.Column(db.Float) profile_pic_id = db.Column(db.Integer, db.ForeignKey('picture.id')) profile_pic = db.relationship("Picture", foreign_keys=[profile_pic_id]) cover_pic_id = db.Column(db.Integer, db.ForeignKey('picture.id')) cover_pic = db.relationship("Picture", foreign_keys=[cover_pic_id]) memberships = db.relationship('Membership', backref='group', lazy='dynamic', foreign_keys='Membership.group_id') members = db.relationship('User', secondary=groups, backref=db.backref('groups', lazy='dynamic', order_by=name), lazy='dynamic') microgroups = db.relationship( 'Group', secondary=group_to_group, primaryjoin=group_to_group.c.microgroup_id == id, secondaryjoin=group_to_group.c.megagroup_id == id, backref="megagroups", remote_side=[group_to_group.c.microgroup_id]) def __init__(self, **kwargs): super(Group, self).__init__(**kwargs) # do custom initialization here self.profile_pic = Picture( path=f"/static/images/groups/{self.handle}/profile_pic", replacement="/static/images/defaults/group.png") self.cover_pic = Picture( path=f"/static/images/groups/{self.handle}/cover_pic", replacement="/static/images/defaults/world.jpg") @hybrid_property def is_microgroup(self): return self.megagroups.count() > 0 @hybrid_property def is_megagroup(self): return self.microgroups.count() > 0 def add_members(self, profiles, permission="member"): for profile in profiles: self.add_member(profile=profile, permission=permission) def add_member(self, profile, permission="member"): self.members.append(profile) membership = Membership(owner=profile, group=self) permission = Permission(title=permission, membership=membership) def remove_member(self, profile): self.members.remove(profile) def remove_members(self, profiles): for profile in profiles: self.remove_member(profile=profile) def set_location(self, location, prelocated=False): if not prelocated: location = geocode(location) if location: self.location = location.address self.latitude = location.latitude self.longitude = location.longitude self.sin_rad_lat = math.sin(math.pi * location.latitude / 180) self.cos_rad_lat = math.cos(math.pi * location.latitude / 180) self.rad_lng = math.pi * location.longitude / 180 return location def member_has_permission(self, profile, permission): if profile in self.members.all(): return self.memberships.filter( Membership.owner == profile, Membership.permissions.any( Permission.title == permission)).count() > 0 return False def __repr__(self): return "<Group {}>".format(self.name)
class APIKey(db.Model): """ Database model that links a user to an API key. This is a one-to-many relationship, a user will get one API key EACH. The number of API keys can be configured in config.py under the variable app_rest_api_key_limit. """ __tablename__ = "api_keys" # As always, everything has an ID. id = db.Column(db.Integer, primary_key=True, autoincrement=True) # This defines to use that there is a column called users.id that links back to the users table to get the user_id user_id = db.Column(db.Integer, db.ForeignKey("users.id")) # The model should also be easy to use, so we define the user itself so the programmer does not have to retrieve the user manually. user = db.relationship("Users", back_populates="api_keys") # We also want to store the API key. Index this for faster results. Finally, we also need a description for the API keys. This is optional. api_key = db.Column(db.String(256), index=True) description = db.Column(db.Text(current_config.app_message_max_length)) # We want to implement the standard function as_json to get the class represented as a dictionary. def as_dict(self): """ Function that returns a representation of the APIKey class as a dictionary which can easily be turned into JSON. """ # Create a new dictionary called ndict to store attributes about the object ndict = {} # Populate the dictionary. We omit 'user' because it is better for there to be less information in each request and we want to follow the standard format of all as_dict functions. ndict['id'] = self.id ndict['user_id'] = self.user_id ndict['api_key'] = self.api_key ndict['description'] = self.description return ndict # Function create_api_key(user, description) @staticmethod def create_api_key(user, description=""): """ This function creates and adds an API key to the database when a user (type Users) is given. The description is optional, it needs to be of type 'str'. The user is given a random API key. This function returns a variable api_key of type 'str'. """ # The way we are going to create a random API key is go through a pool of 62 characters (string.ascii_letters and string.digits) and choose a letter randomly 100 times. letters = string.ascii_letters + string.digits new_api_key = "" # Loop through and add to the new_api_key while removing from the letters. for i in range(100): # Step 1: Choose a letter letter_choice = random.choice(letters) # Step 2: Add to the API key new_api_key += letter_choice # Our new API key is now ready. Now we will add it to the table. new_api_key_entry = APIKey(user=user, api_key=new_api_key, description=description) db.session.add(new_api_key_entry) db.session.commit() # Return the API key at the end. return new_api_key
class User(UserMixin, db.Model): __tablename__ = 'users' def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['ADMIN_EMAIL']: self.role = Roles.query.filter_by(permissions=0xff).first() else: self.role = Roles.query.filter_by(default=True).first() if self.email is not None and self.avatar_hash is None: self.avatar_hash = hashlib.md5( self.email.encode('utf-8')).hexdigest() id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) avatar_hash = db.Column(db.String(32)) posts = db.relationship('Post', backref='author', lazy='dynamic') comments = db.relationship('Comment', backref='author', lazy='dynamic') ''' follow implematation models and helper methods''' followed = db.relationship('Follow', foreign_keys=[Follow.follower_id],\ backref=db.backref('follower', lazy='joined'), lazy='dynamic', \ cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], \ backref=db.backref('followed', lazy='joined'), lazy='dynamic',\ cascade='all, delete-orphan') def follow_u(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self, user): return self.followed.filter_by(followed_id=user.id).first() is not None def is_followed_by(self, user): return self.followers.filter_by( follower_id=user.id).first() is not None ''' permissions helper methods''' def can(self, permissions): return self.role is not None and \ (self.role.permissions & permissions) == permissions def is_administrator(self): return self.can(Permission.ADMINISTER) def gravatar(self, size=100, default='identicon', rating='g'): if request.is_secure: url = 'https://secure.gravatar.com/avatar' else: url = 'http://www.gravatar.com/avatar' hash = self.avatar_hash or hashlib.md5( self.email.encode('utf-8')).hexdigest() return '{url}/{hash}?s={size}&d={default}&r={rating}'.format\ (url=url, hash=hash, size=size, default=default, rating=rating) def __repr__(self): return self.username ''' password setter and verify helper methods''' @property def password(self): raise AttributeError('password aint 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) def generate_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.add(self) return True def ping(self): self.last_seen = datetime.utcnow() db.session.add(self)
class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=True) email = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(255)) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) confirmed = db.Column(db.Boolean, default=False) name = db.Column(db.String(64)) #名字 avatar_hash = db.Column(db.String(32)) #图片的临时缓存hash值 location = db.Column(db.String(64)) #所在地 about_me = db.Column(db.Text()) #关于我 member_since = db.Column(db.DateTime(), default=datetime.utcnow) #注册日期 last_seen = db.Column(db.DateTime(), default=datetime.utcnow) #最后访问日期 posts = db.relationship('Post', backref='author', lazy='dynamic') followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') comments = db.relationship('Comment', backref='author', lazy='dynamic') #关注功能 def follow(self, user): if not self.is_following(user): f = Follow(follower=self, followed=user) db.session.add(f) def unfollow(self, user): f = self.followed.filter_by(followed_id=user.id).first() if f: db.session.delete(f) def is_following(self, user): return self.followed.filter_by(followed_id=user.id).first() is not None def is_followed_by(self, user): return self.followers.filter_by( follower_id=user.id).first() is not None def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['FLASKY_ADMIN']: self.role = Role.query.filter_by(name='Administrator').first() if self.role is None: self.role = Role.query.filter_by(default=True).first() #调用关注函数,自我关注 self.follow(self) #这个是我们程序开发的时候没有考虑到自我关注也一块,后期为了补全功能添加的脚本 @staticmethod def add_self_follows(): for user in User.query.all(): if not user.is_following(user): user.follow(user) db.session.add(user) db.session.commit() @property def password(self): raise AttributeError('password is not a readble attibute') @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) 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.add(self) 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}).decode('utf-8') @staticmethod def reset_password(token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False user = User.query.get(data.get('reset')) if user is None: return False user.password = new_password db.session.add(user) return True def generate_email_change_token(self, new_email, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({ 'change_email': self.id, 'new_email': new_email }).decode('utf-8') def change_email(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token.encode('utf-8')) except: return False if data.get('change_email') != self.id: return False new_email = data.get('new_email') if new_email is None: return False if self.query.filter_by(email=new_email).first() is not None: return False self.email = new_email self.avatar_hash = hashlib.md5(self.email.encode('utf-8')).hexdigest() db.session.add(self) return True def can(self, perm): return self.role is not None and self.role.has_permission(perm) def is_administrator(self): return self.can(Permission.ADMIN) #用户操作记录,每次操作都会调用一下这个函数 def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) #图像生成函数 def gravatar(self, size=100, default='identicon', rating='g'): ''' @param size:图片大小 单位:像素 default:针对没有设置图片的设置默认值 rating:图片级别 ''' if request.is_secure: url = 'https://secure.gravatar.com/avatar' else: url = 'http://www.gravatar.com/avatar' hash = self.avatar_hash or hashlib.md5( self.email.encode('utf-8')).hexdigest() return '{url}/{hash}?s={size}&d={default}&r={rating}'.format( url=url, hash=hash, size=size, default=default, rating=rating) #生成模拟函数 @staticmethod def generate_fake(count=1000): from sqlalchemy.exc import IntegrityError from random import seed import forgery_py seed() for i in range(count): u = User(email=forgery_py.internet.email_address(), username=forgery_py.internet.user_name(True), password=forgery_py.lorem_ipsum.word(), confirmed=True, name=forgery_py.name.full_name(), location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentence(), member_since=forgery_py.date.date(True)) db.session.add(u) try: db.session.commit() except IntegrityError: #判断提交的元素数据是否重复 db.session.rollback() #连表查询,获取关注用户的文章 集合view中的 @property def followed_posts(self): return Post.query.join(Follow, Follow.followed_id == Post.author_id).filter( Follow.follower_id == self.id) #api使用 密令生成,减少密码传递提升安全 def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}) @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.load(token) except: return None return User.query.get(data['id']) #josn字串API使用 def to_json(self): json_user = { 'url': url_for('api.get_post', id=self.id, _external=True), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen, 'posts': url_for('api.get_user_posts', id=self.id, _external=True), 'followed_posts': url_for('api.get_user_followed_posts', id=self.id, _external=True), 'post_count': self.posts.count() } return json_user def __repr__(self): return '<User %r>' % self.usernam
class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer(), primary_key=True) username = db.Column(db.String(64), unique=True, nullable=False) email = db.Column(db.String(64), unique=True, index=True, nullable=False) description = db.Column(db.Text(), nullable=False) location = db.Column(db.String(255), nullable=False) password_hash = db.Column(db.String(255), nullable=False) remember_hashes = db.relationship("Remember", backref="user", lazy="dynamic", cascade="all, delete-orphan") role_id = db.Column(db.Integer(), default=0) gigs = db.relationship("Gig", backref="employer", lazy="dynamic", cascade="all, delete-orphan") applied_gigs = db.relationship("Gig", secondary=applications, backref=db.backref("musicians", lazy="dynamic"), lazy="dynamic") activated = db.Column(db.Boolean(), default=False) activation_hash = db.Column(db.String(255)) activation_sent_at = db.Column(db.DateTime()) def __init__(self, username="", email="", password="", location="", description="", role_id=Role.ADMIN): self.username = username self.email = email self.password_hash = generate_password_hash(password) self.location = location self.description = description self.role_id = role_id if role_id == Role.ADMIN: self.activated = True else: self.activated = False def __repr__(self): return '<User %r>' % self.username @property def password(self): raise AttributeError("Password should not be read like this") @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def is_authenticated(self): return not "" == self.username def is_anonymous(self): return "" == self.username def get_remember_token(self): remember_instance = Remember(self.id) db.session.add(remember_instance) return remember_instance.token def check_remember_token(self, token): if token: for remember_hash in self.remember_hashes: if remember_hash.check_token(token): return True return False def forget(self): self.remember_hashes.delete() def is_admin(self): return self.role_id == Role.ADMIN def is_role(self, role): return self.role_id == role def is_gig_owner(self, gig): return self.id == gig.employer_id def is_applied_to(self, gig): if gig is None: return False return self.applied_gigs.filter_by(id=gig.id).first() is not None def apply(self, gig): if not self.is_applied_to(gig): self.applied_gigs.append(gig) db.session.add(self) def is_active(self): return self.activated def create_activation_token(self): self.activation_token = generate_token() self.activation_hash = generate_hash(self.activation_token) self.activation_sent_at = datetime.utcnow() db.session.add(self)
class User(UserMixin, db.Model): __tablename__ = 'users' __searchable__ = ['username', 'about_me'] __analyzer__ = StemmingAnalyzer() id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True) username = db.Column(db.Unicode(128), unique=True) password_hash = db.Column(db.String(128)) role = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.now) last_seen = db.Column(db.DateTime(), default=datetime.now) avatar_hash = db.Column(db.String(64)) def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['XDANT_ADMIN']: self.role = 'ADMIN' self.confirmed = True else: self.role = 'USER' if self.email is not None and self.avatar_hash is None: self.avatar_hash = '/avatar/%s' % 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) 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.add(self) return True def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}) def reset_password(self, token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('reset') != self.id: return False self.password = new_password db.session.add(self) return True def generate_email_change_token(self, new_email, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'change_email': self.id, 'new_email': new_email}) def change_email(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('change_email') != self.id: return False new_email = data.get('new_email') if new_email is None: return False if self.query.filter_by(email=new_email).first() is not None: return False self.email = new_email self.avatar_hash = hashlib.md5(self.email.encode('utf-8')).hexdigest() db.session.add(self) return True def get_id(self): return u'%s:%s' % (self.role, self.id) def generate_auth_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({"id": self.id}) def send_mail(self): from app.tasks import send_email token = self.generate_auth_token() token_url = url_for('main.confirm', token=token, _external=True) send_email.delay(self.email, "Confirm Your Account", 'auth/confirm', username=self.username, token_url=token_url) @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']) def to_json(self): json_user = { 'url': url_for('api.get_user', id=self.id, _external=True), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen } return json_user def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) def __repr__(self): return '<User %r>' % self.username
class User(db.Model, UserMixin, BaseMixin): __tablename__ = 'users' username = db.Column(db.String(64), nullable=False, index=True) password_hash = db.Column(db.String(128), nullable=False) real_name = db.Column(db.String(64)) email = db.Column(db.String(64), unique=True, index=True, nullable=False) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) last_visited = db.Column(db.DateTime(), default=datetime.utcnow) confirmed = db.Column(db.Boolean, default=False) avatar_hash = db.Column(db.String(32)) avatar_url = db.Column(db.String(256)) role_id = db.Column('role_id', db.Integer, db.ForeignKey('roles.id')) articles = db.relationship('Article', backref='author', lazy='dynamic') comments = db.relationship('Comment', backref='author', lazy='dynamic') collections = db.relationship('Collection', backref='user', lazy='dynamic') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.role is None: if self.email == current_app.config['ADMIN_EMAIL']: self.role = Role.query.filter_by(permissions=0xff).first() if self.role is None: self.role = Role.query.filter_by(name='User').first() if self.email is not None and self.avatar_hash is None: self.avatar_hash = hashlib.md5( self.email.encode('utf-8')).hexdigest() @property def password(self): raise AttributeError('password is not 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) def generate_confirmation_token(self, expiration=60 * 60): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}) def generate_auth_token(self, expiration=60 * 60): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'id': self.id}) @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except Exception: return False return User.query.get(data['id'], None) def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except Exception: return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.add(self) db.session.commit() return True def generate_password_reset_token(self, expiration=60 * 60): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}) def reset_password(self, token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except Exception: return False if data.get('reset') != self.id: return False self.password = new_password db.session.add(self) db.session.commit() return True def generate_email_change_token(self, new_email, expiration=60 * 60): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'change_email': self.id, 'new_email': new_email}) def change_email(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except Exception: return False if data.get('change_email') != self.id: return False new_email = data.get('new_email') if new_email is None: return False if self.query.filter_by(email=new_email).first() is not None: return False self.email = new_email self.avatar_hash = hashlib.md5(self.email.encode('utf-8')).hexdigest() db.session.add(self) db.session.commit() return True def can(self, permissions): return self.role is not None and \ (self.role.permissions & permissions) == permissions def update_last_visited(self): self.last_visited = datetime.utcnow() db.session.add(self) db.session.commit() def get_avatar_url(self, size=100, default='identicon', rating='g'): """从 gravatar 网站获取头像""" if request.is_secure: url = 'http://secure.gravatar.com/avatar' else: url = 'http://www.gravatar.com/avatar' hash_code = hashlib.md5(self.email.encode('utf-8')).hexdigest() return '{url}/{hash_code}?s={size}&d={default}&r={rating}'\ .format(url=url, hash_code=hash_code, size=size, default=default, rating=rating) def follow(self, user): follow = Follow.query.filter_by(followed_id=user.id, follower_id=self.id).first() if follow: follow.update(enable=True) else: follow = Follow(follower_id=self.id, followed_id=user.id) db.session.add(follow) db.session.commit() def unfollow(self, user): follow = Follow.query\ .filter_by(followed_id=user.id, follower_id=self.id, enable=True)\ .first() if follow: follow.update(enable=False) def is_following(self, user): return Follow.query.filter_by(followed_id=user.id, follower_id=self.id, enable=True).first() is not None def is_followed_by(self, user): return Follow.query.filter_by(follower_id=user.id, followed_id=self.id, enable=True).first() is not None @property def followed_articles(self): """获取已关注用户的文章""" return Article.query\ .join(Follow, Follow.followed_id == Article.author_id)\ .filter(Follow.follower_id == self.id) def to_dict(self): return { 'url': url_for('api.get_user', id=self.id, _external=True), 'username': self.username, 'about_me': self.about_me, 'last_visit': self.last_visited, 'articles': url_for('api.get_user_articles', id=self.id, _external=True), 'followed_articles': url_for('api.get_user_followed_articles', id=self.id, _external=True), 'article_count': self.articles.count(), }
class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), nullable=False, index=True) password_hash = db.Column(db.String(128), nullable=False) email = db.Column(db.String(64), nullable=False, index=True) confirmed = db.Column(db.Boolean, default=False) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) register_time = db.Column(db.DateTime(), default=datetime.utcnow) access_time = db.Column(db.DateTime(), default=datetime.utcnow) api_key = db.Column(db.String(128)) devices = db.relationship('Device', backref='user', lazy='dynamic', cascade='all, delete-orphan') warings = db.relationship('Waring', backref='user', lazy='dynamic', cascade='all, delete-orphan') def __str__(self): return '[' + self.name + ':' + str(self.id) + ']' @property def password(self): raise AttributeError('密码不允许读取') @password.setter def password(self, pd): self.password_hash = generate_password_hash(pd) def check_password(self, pd): return check_password_hash(self.password_hash, pd) def generate_token(self, timeout=60): s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY'], timeout) token = s.dumps({'id': self.id}) return token def check_token(self, token): s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False id = data.get('id', None) if id is None: return None user = User.query.filter_by(id=id).first() if user is None: return False user.confirmed = True db.session.add(user) db.session.commit() return True def has_permission(self, permissions): if self.role is None: return False if self.role.permissions & permissions == permissions: return True return False def is_admin(self): return self.has_permission(Permission.ADMIN) def flush_access_time(self): self.access_time = datetime.now() db.session.add(self) db.session.commit() def generate_api(self): s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY'], 60 * 60 * 24 * 365 * 10) self.api_key = s.dumps({'id': self.id}) db.session.add(self) db.session.commit() def check_api(self, api_key): s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY']) try: data = s.loads(api_key) except: return False if data is None: return False id = data.get('id', None) if id is None: return False user = User.query.filter_by(id=id).first() if user is None: return False return True @staticmethod def check_api_key(api_key): s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY']) try: data = s.loads(api_key) except: return False if data is None: return False id = data.get('id', None) if id is None: return False user = User.query.filter_by(id=id).first() if user is None: return False return user
class Email(db.Model): id = db.Column(db.Integer(), primary_key=True) send_date = db.Column(db.DateTime()) recipients = db.Column(db.String(255)) subject = db.Column(db.String(255)) message = db.Column(db.Text())
class HiveDbs(db.Model): __tablename__ = 'hivedbs' id = db.Column(db.Integer, primary_key=True) dbname = db.Column(db.Text()) dbdesc = db.Column(db.Text()) layer = db.Column(db.Text()) dictname = db.Column(db.Text()) owner = db.Column(db.Text()) pdbname = db.Column(db.Text()) grantuser = db.Column(db.Text()) creator = db.Column(db.Text()) modifier = db.Column(db.Text()) createtime = db.Column(db.Text()) modifytime = db.Column(db.Text()) @staticmethod def from_json(hive_db_json): dbname = hive_db_json.get('name') dbdesc = hive_db_json.get('intro') layer = hive_db_json.get('layer') owner = hive_db_json.get('owner') pdbname = hive_db_json.get('mapedb') grantuser = hive_db_json.get('granted') creator = hive_db_json.get('creator') modifier = hive_db_json.get('modifier') createtime = hive_db_json.get('createtime') modifytime = hive_db_json.get('createtime') return HiveDbs(dbname=dbname, dbdesc=dbdesc, layer=layer, owner=owner, pdbname=pdbname, grantuser=grantuser, creator=creator, modifier=modifier, createtime=createtime, modifytime=modifytime)
class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) full_name = db.Column(db.String(255), nullable=True) email = db.Column(db.String(255), unique=True, nullable=False) password = db.Column(db.String(255), nullable=False) avatar = db.Column(db.Text(), nullable=True) phone_number = db.Column(db.String(20), unique=True) # status = db.Column(TINYINT(), doc="0. block, 1.active",server_default="1", nullable=False) status = db.Column(db.Numeric(4, asdecimal=False), doc="0. block, 1.active", server_default="1", nullable=False) username = db.Column(db.String(120), unique=True, nullable=False) email_verified_at = db.Column(db.TIMESTAMP(), nullable=True) remember_token = db.Column(db.String(120), nullable=True) created_at = db.Column(db.TIMESTAMP(), nullable=True, server_default=db.func.now()) updated_at = db.Column(db.TIMESTAMP(), nullable=True, server_default=db.func.now(), server_onupdate=db.func.now()) deleted_at = db.Column(db.TIMESTAMP(), nullable=True) posts = db.relationship('Post', lazy='select', backref=db.backref('author', lazy='joined')) def __init__(self, name, email, username, password): self.name = name self.email = email self.username = username self.password = bcrypt.generate_password_hash(password, 10).decode('utf-8') # @classmethod # def __declare_last__(cls): # ValidateString(User.name) # ValidateEmail(User.email, True, True, "The e-mail is not valid. Please check it") #genarate hash pasword def generatePasswordHash(password): return bcrypt.generate_password_hash(password, 10).decode('utf-8') def verifyPassword(self, password): myPassword = self.password if hasattr(myPassword, 'decode'): myPassword = myPassword.decode() return bcrypt.check_password_hash(myPassword, password) # funtion def delete(self): db.session.delete(self) db.session.commit() #JWT def encodeAuthToken(self, user_id): """ Generates the Auth Token :return: string """ try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=36000), 'iat': datetime.datetime.utcnow(), 'user_id': user_id } return jwt.encode(payload, app.config.get('SECRET_KEY'), algorithm='HS256') except Exception as e: return e #decode auth token @staticmethod def decodeAuthToken(auth_token): """ Decodes the auth token :param auth_token: :return: integer|string """ try: payload = jwt.decode(auth_token, app.config.get('SECRET_KEY')) return payload['user_id'] except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again.' except jwt.InvalidTokenError: return 'Invalid token. Please log in again.'
class Collection(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) title = db.Column(db.String(128)) description = db.Column(db.Text()) category = db.Column(db.String(64)) published = db.Column(db.Boolean()) publish_date = db.Column(db.DateTime()) thumbnail = db.Column(db.Text()) articles = db.relationship('CollectionArticle', backref='collection', lazy='dynamic') images = db.relationship('CollectionImage', backref='collection', lazy='dynamic') def get_thumbnail(self): if self.thumbnail and self.thumbnail != "": return self.thumbnail else: if self.get_num_images > 0: for i in self.images: a = Image.query.get(i.image_id) return a.image for i in self.articles: a = Article.query.get(i.article_id) if a.lead_image: return a.lead_image return "http://ruon.tv/wp-content/uploads/2014/02/default-image.png" # TODO, get real placeholder image def dictionary(self): return { 'id': str(self.id), 'title': self.title, 'description': self.description, 'category': self.category, 'published': self.published, 'publish_date': self.publish_date, 'thumbnail': self.get_thumbnail(), 'items': self.items_dict(), 'creator': self.get_user(), 'user_id': self.user_id, } def items_dict(self): items = [None for i in xrange(self.get_num_items())] for article in self.articles: d = {'id': str(article.article_id), 'type': 'article'} items[article.order] = d for image in self.images: d = {'id': str(image.image_id), 'type': 'image'} items[image.order] = d return items def get_num_items(self): a = [None for _ in self.articles] i = [None for _ in self.images] return len(a) + len(i) def get_num_images(self): return len([None for _ in self.images]) def get_user(self): return User.query.get(self.user_id).username