class Meet(db.Model): """ 会议室的信息 """ __tablename__ = 'meet' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(225)) password = db.Column(db.String(20)) password_hash = db.Column(db.String(225)) meet_portrait = db.Column(db.String(128)) create_time = db.Column(db.DateTime()) start_time = db.Column(db.DateTime()) attachment = db.Column(db.String(225)) end_time = db.Column(db.DateTime()) meet_message = db.Column(db.String(255)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) msgs = db.relationship('ChatMessage', backref='meets') # ---password hash @property def password(self): raise AttributeError('password is not a readable attributes') @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) # ---password hash def __init__(self, **kwargs): super(Meet, self).__init__(**kwargs) self.create_time = datetime.now() def __str__(self): return "<Meet {}> created in {}".format(self.name, self.create_time) def __repr__(self): return "<Meet {}> created in {}".format(self.name, self.create_time)
class Comment(db.Model): __tablename__ = 'comment' __table_args__ = {'mysql_charset': 'utf8'} id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(255), nullable=False) text = db.Column(db.Text(), nullable=False) date = db.Column(db.DateTime()) remark = db.Column(db.String(255)) post_id = db.Column(db.Integer, db.ForeignKey('post.id')) def __repr__(self): return "<Comment '{}'>".format(self.text[:15])
class ChatMessage(db.Model): """ 记录聊天的message """ __tablename__ = 'chat_message' id = db.Column(db.Integer, primary_key=True) message = db.Column(db.Text) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) meet_id = db.Column(db.Integer, db.ForeignKey('meet.id')) create_time = db.Column(db.DateTime()) def __init__(self, **kwargs): super(ChatMessage, self).__init__(**kwargs) self.create_time = datetime.now() def __str__(self): return "<ChatRoom {}>".format(Meet.query.get(self.meet_id).name) def __repr__(self): return "<ChatRoom {}>".format(Meet.query.get(self.meet_id).name)
class User(db.Model, UserMixin, BaseMixin): __tablename__ = 'users' bio = db.Column(db.String(128), default='') name = db.Column(db.String(128), default='') nickname = db.Column(db.String(128), default='') email = db.Column(db.String(191), default='') password = db.Column(db.String(191)) website = db.Column(db.String(191), default='') github_id = db.Column(db.String(191), default='') last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(100)) current_login_ip = db.Column(db.String(100)) login_count = db.Column(db.Integer) active = db.Column(db.Boolean()) icon_color = db.Column(db.String(7)) confirmed_at = db.Column(db.DateTime()) company = db.Column(db.String(191), default='') avatar_id = db.Column(db.String(20), default='') roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) __table_args__ = ( db.Index('idx_name', name), db.Index('idx_email', email), ) def url(self): return '/user/{}'.format(self.id) @property def avatar_path(self): avatar_id = self.avatar_id return '' if not avatar_id else '/static/avatars/{}.png'.format( avatar_id) def update_avatar(self, avatar_id): self.avatar_id = avatar_id self.save() def upload_avatar(self, img): avatar_id = generate_id() filename = os.path.join(UPLOAD_FOLDER, 'avatars', '{}.png'.format(avatar_id)) if isinstance(img, str) and img.startswith('http'): r = requests.get(img, stream=True) if r.status_code == 200: with open(filename, 'wb') as f: for chunk in r.iter_content(1024): f.write(chunk) else: img.save(filename) self.update_avatar(avatar_id) def follow(self, from_id): ok, _ = Contact.create(to_id=self.id, from_id=from_id) if ok: self._stats = None return ok def unfollow(self, from_id): contact = Contact.get_follow_item(from_id, self.id) if contact: contact.delete() self._stats = None return True return False def is_followed_by(self, user_id): contact = Contact.get_follow_item(user_id, self.id) return bool(contact)
class User(db.Model): __tablename__ = 'users' __table_args__ = {'mysql_charset': 'utf8mb4'} id = db.Column(db.Integer, primary_key=True) sex = db.Column(db.SmallInteger, default=2) nick_name = db.Column(db.String(60), index=True) password = db.Column(db.String(255)) phone = db.Column(db.String(20)) email = db.Column(db.String(40)) signature = db.Column(db.String(512), default='') province = db.Column(db.String(20), default='') city = db.Column(db.String(20), default='') active = db.Column(db.Boolean()) login_time = db.Column(db.Integer) confirmed_at = db.Column(db.DateTime()) last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(63)) current_login_ip = db.Column(db.String(63)) login_count = db.Column(db.Integer) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users')) #, lazy='dynamic')) groups = db.relationship('Group', secondary=group_relationship, backref='members') mps = db.relationship('MP', secondary=mp_relationship, backref='users') friends = db.relationship('User', secondary=friendship, primaryjoin=(friendship.c.user_id == id), secondaryjoin=(friendship.c.friend_id == id), lazy='dynamic') def __repr__(self): return '<User %r>' % self.nick_name def to_json(self): json_user = { 'id': self.id, 'nickname': self.nick_name, 'phone': self.phone, 'email': self.email, 'signature': self.signature, 'province': self.province, 'signature': self.signature, 'city': self.city } return json_user def hash_password(self, password): self.password = pwd_context.encrypt(password) def verify_password(self, password): return pwd_context.verify(password, self.password) def generate_auth_token(self, expiration=600): s = Serializer(app.app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}) def get(self, id): return self.query.filter_by(id=id).first() def update(self): return session_commit() @staticmethod def verify_auth_token(token): s = Serializer(app.app.config['SECRET_KEY']) try: data = s.loads(token) except SignatureExpired: return None # valid token, but expired except BadSignature: return None # invalid token user = User.query.get(data['id']) return user @hybrid_method def add_friend(self, user): if not self.is_friend(user): self.friends.append(user) user.friends.append(self) return self @hybrid_method def del_friend(self, user): if self.is_friend(user): self.friends.remove(user) user.friends.remove(self) return self @hybrid_method def is_friend(self, user): return self.friends.filter( friendship.c.friend_id == user.id).count() > 0 @hybrid_method def add_group(self, group): if not self.is_in_group(group): self.groups.append(group) @hybrid_method def del_group(self, group): if self.is_in_group(group): self.groups.remove(group) @hybrid_method def is_in_group(self, group): return group in self.groups
class User(db.Model): """ 会议的用户表和管理员表 id 编号 username 用户名 password 密码(不可见) password_hash 储存password的hash码 email 仅一个 phone 电话号码 仅一个 company 人员所属公司 meets 关联的会议信息表 create_time 用户创建时间 msgs 关联 聊天记录 verify_password 验证密码 generate_auth_token 生成token verify_auth_token 验证token """ __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) head_portrait = db.Column(db.String(128), default='file/head_portrait.jpg') username = db.Column(db.String(25), unique=True) password = db.Column(db.String(25)) password_hash = db.Column(db.String(225)) email = db.Column(db.String(30), unique=True) phone = db.Column(db.String(15), unique=True) company = db.Column(db.String(50)) meets = db.relationship('Meet', backref='users', lazy='dynamic') create_time = db.Column(db.DateTime()) msgs = db.relationship('ChatMessage', backref='users') role_id = db.Column(db.Integer, db.ForeignKey('role.id')) # ---password hash @property def password(self): raise AttributeError('password is not a readable attributes') @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) # ---password hash def generate_auth_token(self, expiration=6000): s = Serializer(BaseConfig.SECRET_KEY, expires_in=expiration) return s.dumps({'id': self.id}) @staticmethod def verify_auth_token(token): s = Serializer(BaseConfig.SECRET_KEY) try: data = s.loads(token) except SignatureExpired: return None # valid token, but expired except BadSignature: return None # invalid token user = User.query.get(data['id']) return user def can(self, permission): return self.role is not None and (self.role.permissions & permission) == permission def is_meeter(self): """ 判断是否为会议的创建者 permissions == 3 """ return self.can(Permission.USER | Permission.MEETER) def is_admin(self): """ 判断是否系统管理员 permissions == 255 """ return self.can(Permission.ADMINISTRATOR) def __init__(self, **kwargs): super(User, self).__init__(**kwargs) self.create_time = datetime.now() def __str__(self): return "<User: {} id: {}>".format(self.username, self.id) def __repr__(self): return "<User {} id: {}>".format(self.username, self.id)
class User(db.Model, UserMixin, BaseMixin): __tablename__ = "users" bio = db.Column(db.String(128), default="") name = db.Column(db.String(128), default="") nickname = db.Column(db.String(128), default="") email = db.Column(db.String(191), default="") password = db.Column(db.String(191)) website = db.Column(db.String(191), default="") github_id = db.Column(db.String(191), default="") last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(100)) current_login_ip = db.Column(db.String(100)) login_count = db.Column(db.Integer) active = db.Column(db.Boolean()) icon_color = db.Column(db.String(7)) confirmed_at = db.Column(db.DateTime()) company = db.Column(db.String(191), default="") avatar_id = db.Column(db.String(20), default="") roles = db.relationship("Role", secondary=roles_users, backref=db.backref("users", lazy="dynamic")) _stats = None __table_args__ = (db.Index("idx_name", name), db.Index("idx_email", email)) def url(self): return f"/user/{self.id}" @property def avatar_path(self): avatar_id = self.avatar_id return "" if not avatar_id else f"/static/avatars/{avatar_id}.png" def update_avatar(self, avatar_id): self.avatar_id = avatar_id self.save() def upload_avatar(self, img): avatar_id = generate_id() filename = UPLOAD_FOLDER / "avatars" / f"{avatar_id}.png" if isinstance(img, str) and img.startswith("http"): r = requests.get(img, stream=True) if r.status_code == 200: with open(filename, "wb") as f: for chunk in r.iter_content(1024): f.write(chunk) else: with open(filename, "wb") as f: img.save(f) self.update_avatar(avatar_id) def follow(self, from_id): ok, _ = Contact.create(to_id=self.id, from_id=from_id) if ok: self._stats = None return ok def unfollow(self, from_id): contact = Contact.get_follow_item(from_id, self.id) if contact: contact.delete() self._stats = None return True return False def is_followed_by(self, user_id): contact = Contact.get_follow_item(user_id, self.id) return bool(contact) @property def n_followers(self): return self._follow_stats[0] @property def n_following(self): return self._follow_stats[1] @property def _follow_stats(self): if self._stats is None: stats = userFollowStats.get(self.id) if not stats: self._stats = 0, 0 else: self._stats = stats.follower_count, stats.following_count return self._stats