class User(DictMixin, db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(128)) name = db.Column(db.String(64)) tel = db.Column(db.String(64)) about = db.Column(db.Text()) position = db.Column(db.Text()) role_id = db.Column(db.Integer, default=Role.MANAGER.value) group_id = db.Column(db.Integer, db.ForeignKey('group.id')) created_time = db.Column(db.DateTime, default=datetime.datetime.utcnow()) updated_time = db.Column(db.DateTime, default=datetime.datetime.utcnow()) status = db.Column(db.Integer, default=0) @property def password(self): return self.password_hash # @property # def email(self): # return self.email # @email.setter # def email(self, email): # self.email = email.lower() @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_auth_token(self, expiration=3600 * 24): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({ 'id': self.id, 'expire_time': now() + expiration }).decode('utf-8') @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) refresh_token_or_not = True if now() + 600 >= data.get( 'expire_time') else False except: return None, None return User.query.get(data['id']), refresh_token_or_not
class Reply(DictMixin, db.Model): id = db.Column(db.Integer, primary_key=True) comment_id = db.Column(db.Integer, db.ForeignKey('comment.id')) content = db.Column(db.Text(512)) from_uid = db.Column(db.Integer, db.ForeignKey('user.id')) to_uid = db.Column(db.Integer, db.ForeignKey('user.id')) at = db.Column(db.String(32)) created_time = db.Column(db.DateTime, default=datetime.datetime.utcnow())
class User(db.Model): # __tablename__ = 't_user' uid = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), index=True, unique=True, nullable=True) weight = db.Column(db.Float(10, 2)) # # decimal money = db.Column(db.Numeric(10, 2)) create_date = db.Column(db.DateTime, default=datetime.datetime.now()) # # 不要在text字段上面加索引 msg = db.Column(db.Text())
class Blog(db.Model): __tablename__ = 'blogs' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(50), nullable=False) content = db.Column(db.Text(), nullable=False) pubTime = db.Column(db.BigInteger, index=True) user_id = db.Column(db.Integer, nullable=False) def __init__(self, title, content, uid): self.title = title self.content = content self.pubTime = int(time.time() * 1000) self.user_id = uid def to_json(self): json_blog = self.__dict__.copy() json_blog.pop('_sa_instance_state') return json_blog
class User(DictMixin, db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(128)) name = db.Column(db.String(64)) tel = db.Column(db.String(64)) about = db.Column(db.Text()) position = db.Column(db.Text()) role_id = db.Column(db.Integer, default=Role.MANAGER.value) group_id = db.Column(db.Integer, db.ForeignKey('group.id')) @staticmethod def generate_fake(count=5): 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()) db.session.add(u) try: db.session.commit() except IntegrityError: db.session.rollback() @property def password(self): return self.password_hash @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_auth_token(self, expiration=3600 * 24): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({ 'id': self.id, 'expire_time': now() + expiration }).decode('utf-8') @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) refresh_token_or_not = True if now() + 600 >= data.get( 'expire_time') else False except: return None, None return User.query.get(data['id']), refresh_token_or_not
class Comment(DictMixin, db.Model): id = db.Column(db.Integer, primary_key=True) task_id = db.Column(db.Integer, db.ForeignKey('task.id')) content = db.Column(db.Text(512)) from_uid = db.Column(db.Integer, db.ForeignKey('user.id')) created_time = db.Column(db.DateTime, default=datetime.datetime.utcnow())
class Document(Base): """ 文档表 """ __tablename__ = "documents" uuid = db.Column(db.String(100), nullable=False, comment="别名", unique=True, index=True) title = db.Column(db.String(100), nullable=False, comment="文档标题", unique=True) use_title = db.Column(db.String(100), comment="文档标题带样式") sub_title = db.Column(db.String(100), nullable=False, comment="副标题") keyword = db.Column(db.String(255), default="", comment="META关键字") description = db.Column(db.String(255), default="", comment="META描述") label = db.Column(db.String(255), default="", comment="摘要") external_link = db.Column(db.String(100), default="", comment="外部链接") published_at = db.Column(db.DateTime(), default="", comment="发布时间") thumb_image = db.Column(db.String(100), default="", comment="缩略图") author = db.Column(db.String(20), default="", comment="作者") source = db.Column(db.String(100), default="", comment="来源") source_link = db.Column(db.String(100), default="", comment="来源链接") attribute = db.Column(db.String(100), default="", comment="属性") content = db.Column(db.Text(), default="", comment="正文") tags = db.Column(db.String(100), default="", comment="标签", index=True) target = db.Column(db.Boolean(), default=0, comment="新窗口打开") click = db.Column(db.Integer(), default=0, comment="阅读数") editor = db.Column(db.String(100), default="", comment="编辑") is_original = db.Column(db.Boolean(), default=0, comment="是否原创") open_comment = db.Column(db.Boolean(), default=0, comment="允许评论") attach_file = db.Column(db.String(100), default="", comment="附件地址") attach_name = db.Column(db.String(100), default="", comment="附件名称") column_id = db.Column(db.Integer(), db.ForeignKey('columns.id'), comment="栏目id") admin_id = db.Column(db.Integer(), db.ForeignKey('admins.id'), comment="管理员id") column = db.relationship('Column', backref=db.backref('documents', lazy="dynamic")) admin = db.relationship('Admin', backref=db.backref('documents', lazy="dynamic")) login_show = db.Column(db.Boolean(), default=0, comment="登录可见") password_txt = db.Column(db.String(100), default=0, comment="不为空为密码可见") user_group = db.Column(db.Boolean(), default=0, comment="VIP可见") @classmethod def _query_search(cls, query, _keyword): if _keyword is not None: keyword = '%' + str(_keyword) + '%' return query.filter( or_( cls.title.like(keyword), cls.label.like(keyword), cls.keyword.like(keyword), cls.description.like(keyword), cls.author.like(keyword), )) return query def create(self, data): attributes = request.form.getlist('attribute[]') with db.auto_commit(): self.set_attrs(data) self.active = 1 self.admin = current_user self.attribute = ",".join(attributes) self.created_at = time_now() self.updated_at = time_now() db.session.add(self) def update(self, data, edit_one_field=None): """ edit_one_field 是否表内单个编辑 标识 :param data: :param flag: :return: """ attributes = request.form.getlist('attribute[]') with db.auto_commit(): if not edit_one_field: self.set_attrs(data) self.attribute = ",".join(attributes) else: self.set_attr(data) self.updated_at = time_now()
class BaseDocument(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text()) features = db.Column(db.ARRAY(db.Float())) wc = db.Column(db.Integer) def __init__(self, text): self.text = text self.wc = wc @property def json(self): return { "text": self.text, "features": self.features, "wc": self.wc } def compute_features(self): # Duplicate every apostrophe: this is for PostgreSQL, since apostrophe's are escaped by themselves text = self.text.replace("'", "''") # Split the text into words and get the document's count for every word words = text.split(" ") count = Counter(words) vocab = list(count.keys()) total = np.zeros(FEATURES) sub = np.zeros(FEATURES) # Set up query input: ["Hello", "world"] => '{"Hello", "world"}' q = '{"' + '", "'.join(vocab) + '"}' # Get word features and convert to dictionary wordfs = db.session.execute(f"SELECT * FROM match_words('{q}');").fetchall() #! approx 0.2second/1k words wordfs = {x[0]: x[1:] for x in wordfs} for word in wordfs: wordf = wordfs[word] # Convert wordf into a numpy array called new new = np.array(wordf, dtype=float) # Keep track of zero-valued continuous features sub += ((FLOATS == True) & np.isnan(new)) * count[word] # Aggregate feature values within total total += np.nan_to_num(new, 0) * count[word] # set(count) - set(wordfs) is the set of words in the document not in the Words table for word in set(count) - set(wordfs): sub += (FLOATS == True) * count[word] # For categoricals: calculate the average, and thus probability of words belonging to a given category, by total / |D| # For continuous values: calculate the non-zero average (this is why `sub` is needed!) # It can be the case that len(words) = sub, that is to say a division by 0 may be imminent. # This happens when a continuous value is always None for a given document. We don't really care for this and we can just ignore it. # If this were to happen though, make sure to convert them to 0. with np.errstate(divide='ignore',invalid='ignore'): total = total / (len(words) - sub).astype('float') total = np.nan_to_num(total, 0) total = total.tolist() # average word length is a last-second feature, deal with double apostrophe # avg_word_len = (sum(map(len, words)) - text.count("''")) / float(len(words)) # total.append(avg_word_len) self.features = total return self.features