class Notification(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128), index=True) user_id = db.Column(db.Integer, db.ForeignKey(User.id)) timestamp = db.Column(db.Float, index=True, default=time) payload_json = db.Column(db.Text) def get_data(self): return json.loads(str(self.payload_json))
class Message(db.Model): id = db.Column(db.Integer, primary_key=True) sender_id = db.Column(db.Integer, db.ForeignKey(User.id)) recipient_id = db.Column(db.Integer, db.ForeignKey(User.id)) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow()) def __repr__(self): return '<Message {}>'.format(self.body)
class Post(SearchableMixin, db.Model): id = db.Column(db.Integer, primary_key=True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey(User.id)) language = db.Column(db.String(5)) __searchable__ = ['body'] def __repr__(self): return '<Post {}>'.format(self.body)
class Xt(db.Model): __tablename__ = 'Xt' __table_args__ = {'mysql_collate': 'utf8_general_ci'} number = db.Column(db.Integer, autoincrement=True, primary_key=True) # 需要使用__tablename__参数指定表名 u_id = db.Column(db.Integer, db.ForeignKey('User.id'), nullable=True) xt = db.Column(db.Integer) x_date = db.Column(db.DateTime) def __repr__(self): return 'id:%s, xt:%s, x_date:%s' % (self.u_id, self.xt, self.x_date)
class Task(db.Model): id = db.Column(db.String(36), primary_key=True) name = db.Column(db.String(128), index=True) description = db.Column(db.String(128)) user_id = db.Column(db.Integer, db.ForeignKey(User.id)) complete = db.Column(db.Boolean, default=False) def get_rq_job(self): try: job = rq.job.Job.fetch(self.id, connection=current_app.redis) except (redis.exceptions.RedisError, rq.exceptions.NoSuchJobError): return None return job def get_progress(self): job = self.get_rq_job() return job.meta.get('progress', 0) if job is not None else 100
class User(db.Model): __tablename__ = 'User' # 指明表名,默认与类相同 __table_args__ = {'mysql_collate': 'utf8_general_ci'} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) sex = db.Column(db.String(4)) age = db.Column(db.Integer) sg = db.Column(db.Integer) addr = db.Column(db.String(64)) tel = db.Column(db.String(11)) date_c = db.Column(db.DateTime) xy = db.relationship("Xy", backref='User') xt = db.relationship("Xt", backref='User') # relationship() 把两个表关联在一起,不添加也是可以的,根据自己的需求 def __repr__(self): return 'name:%r' % (self.name)
class User(PaginatedAPIMixin, UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) # email = db.Column(db.String(120), index=True, unique=True) email = db.Column(db.String(120), index=True) password_hash = db.Column(db.String(128)) about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime, default=datetime.utcnow) token = db.Column(db.String(32), unique=True, index=True) token_expiration = db.Column(db.DateTime) posts = db.relationship('Post', backref='author', lazy='dynamic') 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') sent_messages = db.relationship('Message', backref='author', foreign_keys='Message.sender_id', lazy='dynamic') received_messages = db.relationship('Message', backref='recipient', foreign_keys='Message.recipient_id', lazy='dynamic') last_message_read_time = db.Column(db.DateTime) notifications = db.relationship('Notification', backref='user', lazy='dynamic') tasks = db.relationship('Task', backref='user', lazy='dynamic') def __repr__(self): return '<User {}>'.format(self.username) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def avatar(self, size): digest = md5(self.email.lower().encode('utf-8')).hexdigest() return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format( digest, size) def follow(self, user): if not self.is_following(user): self.followed.append(user) def unfollow(self, user): if self.is_following(user): self.followed.remove(user) def is_following(self, user): return self.followed.filter( followers.c.followed_id == user.id).count() > 0 def followed_posts(self): followed = Post.query.join( followers, (followers.c.followed_id == Post.user_id)).filter( followers.c.follower_id == self.id) own = Post.query.filter_by(user_id=self.id) return followed.union(own).order_by(Post.timestamp.desc()) def get_reset_password_token(self, expires_in=600): return jwt.encode( { 'reset_password': self.id, 'exp': time() + expires_in }, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8') def new_messages(self): last_read_time = self.last_message_read_time or datetime(1900, 1, 1) return Message.query.filter_by(recipient=self).filter( Message.timestamp > last_read_time).count() @staticmethod def verify_reset_password_token(token): try: id = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password'] except: return return User.query.get(id) def add_notification(self, name, data): self.notifications.filter_by(name=name).delete() n = Notification(name=name, payload_json=json.dumps(data), user=self) db.session.add(n) return n def launch_task(self, name, description, *args, **kwargs): rq_job = current_app.task_queue.enqueue('appm.tasks.' + name, self.id, *args, **kwargs) task = Task(id=rq_job.get_id(), name=name, description=description, user=self) db.session.add(task) return task def get_tasks_in_progress(self): return Task.query.filter_by(user=self, complete=False).all() def get_task_in_progress(self, name): return Task.query.filter_by(name=name, user=self, complete=False).first() def to_dict(self, include_email=False): data = { 'id': self.id, 'username': self.username, 'last_seen': self.last_seen.isoformat() + 'Z', 'about_me': self.about_me, 'post_count': self.posts.count(), 'follower_count': self.followers.count(), 'followed_count': self.followed.count(), '_links': { 'self': url_for('api.get_user', id=self.id), 'followers': url_for('api.get_followers', id=self.id), 'followed': url_for('api.get_followed', id=self.id), 'avatar': self.avatar(128) } } if include_email: data['email'] = self.email return data def from_dict(self, data, new_user=False): for field in ('username', 'about_me', 'email'): if field in data: setattr(self, field, data[field]) if new_user and 'password' in data: self.set_password(data['password']) def get_token(self, expires_in=3600): now = datetime.utcnow() if self.token and self.token_expiration > now + timedelta(seconds=60): return self.token self.token = base64.b64encode(urandom(24)).decode('utf-8') self.token_expiration = now + timedelta(seconds=expires_in) db.session.add(self) return self.token def revoke_token(self): self.token_expiration = datetime.utcnow() - timedelta(seconds=1) @staticmethod def check_token(token): user = User.query.filter_by(token=token).first() if user is None or user.token_expiration < datetime.utcnow(): return None return user
'total_pages': resources.pages, 'total_items': resources.total }, '_links': { 'self': url_for(endpoint, page=page, per_page=per_page, **kwargs), 'next': url_for(endpoint, page=page + 1, per_page=per_page, **kwargs) \ if resources.has_next else None, 'prev': url_for(endpoint, page=page - 1, per_page=per_page, **kwargs) \ if resources.has_prev else None } } return data followers = db.Table( 'followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))) class User(PaginatedAPIMixin, UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=True) # email = db.Column(db.String(120), index=True, unique=True) email = db.Column(db.String(120), index=True) password_hash = db.Column(db.String(128)) about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime, default=datetime.utcnow) token = db.Column(db.String(32), unique=True, index=True) token_expiration = db.Column(db.DateTime) posts = db.relationship('Post', backref='author', lazy='dynamic') followed = db.relationship('User',