Beispiel #1
0
class User(UserMixin, db.Model):
    """User Model """

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)
    firstname = db.Column(db.String(100), nullable=False)
    lastname = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(250), unique=True, nullable=False)
    posts = db.relationship('Post', backref=db.backref('posts', lazy=True))
    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')
    created_on = db.Column(db.DateTime, default=datetime.utcnow)

    def set_password(self, password):
        """Create User Password """
        self.password = generate_password_hash(password, method='sha256')

    def check_password(self, password):
        """Check Hashed Password"""
        return check_password_hash(self.password, password)

    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

    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:
            f = self.followed.filter_by(followed_id=user.id).first()
            db.session.delete(f)
            return True

    def __repr__(self):
        return '<User {}>'.format(self.username)
Beispiel #2
0
class User(db.Model, fsqla.FsUserMixin):
    # __tablename__ = 'tb_sy_user'
    name = db.Column(db.String(100))
    sex = db.Column(db.String(1))
    age = db.Column(db.Integer)

    logs = db.relationship("AnalysesLog", backref=db.backref("user"))

    @staticmethod
    def data_table_fields() -> list:
        """
        数据表的字段列表
        Returns:

        """
        return ["id", "username", "s_name", "last_login_date"]

    def to_dict(self):
        return {
            "id": self.id,
            "s_name": self.name,
            "username": self.username,
            "last_login_date": self.last_login_at,
            "access": self.roles[0].name
        }
Beispiel #3
0
class Permission(db.Model):
    __tablename__ = 'permissions'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    roles = db.relationship(
        'Role',
        secondary=roles_permissions,
        backref=db.backref('permissions', lazy='dynamic'))
Beispiel #4
0
class Post(db.Model, CRUDMixin, TimeMixin):
    id = db.Column(db.UUID(as_uuid=True), default=uuid.uuid4, primary_key=True)
    author_id = db.Column(db.String, db.ForeignKey('user.id'))
    type = db.Column(db.String)  # lost or found
    tags = db.Column(db.ARRAY(db.String, dimensions=1))
    title = db.Column(db.String)
    category = db.Column(db.String)
    content = db.Column(db.String)
    img_URLs = db.Column(postgresql.ARRAY(db.String, dimensions=1))
    site = db.Column(db.String)
    hit = db.Column(db.Integer, default=0)
    author = db.relationship('User', backref=db.backref(
        'posts', lazy=True))
Beispiel #5
0
class Room(db.Model, CRUDMixin):
    __tablename__ = 'room'
    id = db.Column(db.UUID(as_uuid=True), default=uuid.uuid4, primary_key=True)
    group = db.Column(db.String())
    campus = db.Column(db.String())
    building = db.Column(db.String)
    floor = db.Column(db.Integer)
    no = db.Column(db.Integer)
    capacity = db.Column(db.Integer)
    name = db.Column(db.String(80), nullable=False)
    detail = db.Column(db.String(80), nullable=False)
    available = db.Column(db.Boolean, default=True)
    orders = db.relationship('Order',
                             lazy='select',
                             backref=db.backref('room', lazy=True))
Beispiel #6
0
class Organisation(db.Model):
    organisation = db.Column(db.String(64), primary_key=True)    # government-organisation:D6
    name = db.Column(db.String(256))
    website = db.Column(db.String(256))
    text = db.Column(db.Text)
    feature_id = db.Column(db.String(256), ForeignKey('feature.feature', name='organisation_feature_fkey'))
    feature = db.relationship('Feature', uselist=False)

    category_id = db.Column(db.String(64), ForeignKey('category.category', name='organisation_category_fkey'))
    publications = db.relationship('Publication', backref='organisation', lazy=True)

    other_features = db.relationship('Feature',
                                     lazy='dynamic',
                                     secondary=organisation_feature,
                                     primaryjoin='Organisation.organisation == organisation_feature.columns.organisation',
                                     secondaryjoin='Feature.feature == organisation_feature.columns.feature',
                                     backref=db.backref('organisation', lazy=True))
Beispiel #7
0
class User(UserMixin, db.Model, CRUDMixin, TimeMixin):
    id = db.Column(db.String(), primary_key=True)
    open_id = db.Column(db.String())
    name = db.Column(db.String(), index=True)
    username = db.Column(db.String(80))
    nickname = db.Column(db.String())
    email = db.Column(db.String())
    phone = db.Column(db.String())
    avatar_URL = db.Column(db.String(), default='avatar_default.jpg')
    last_login = db.Column(db.DateTime, nullable=False,
                           default=datetime.now)
    activated = db.Column(db.Boolean)
    robot = db.Column(db.Boolean)
    pw_hash = db.Column(db.String())
    oauth = db.relationship('SocialOAuth', lazy='select',
                            backref=db.backref('user', lazy=True))
    user_type = db.Column(db.String, default='user')
    extra = db.Column(db.JSON)
    __mapper_args__ = {
        'polymorphic_identity': 'user',
        'polymorphic_on': user_type
    }

    @staticmethod
    def is_teacher_id(user_id):
        return user_id.startswith("100") or user_id.startswith("510") or user_id.startswith("310") or user_id.startswith("610")

    @staticmethod
    def is_student_id(user_id):
        return user_id[2:4] == '12' or user_id[2:4] == '17':

    def authenticate(self, password):
        if check_password_hash(self.pw_hash, password):
            return True
        else:
            return False

    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'])

    def regisiter(self, password):
        client = Services(self.id, password)
        if client.login() and client.get_data():
            self.name = client.data['name']
            self.username = client.data['nickname']
            self.pw_hash = generate_password_hash(password)
            self.save()
            return True
        else:
            return False

    def get_id(self):
        return self.id

    def __unicode__(self):
        return self.name + str(self.id)

    def to_dict_public(self):
        return {
            'avatarURL': self.avatar_URL,
            'id': self.id,
            'name': self.nickname
        }

    @property
    def display_name(self):
        return self.name

    def to_dict(self):
        result = {
            'id': self.id,
            'avatarURL': self.avatar_URL,
            'name': self.name,
            'nickname': self.nickname,
            'email': self.email,
            'lastLogin': str(self.last_login),
            'username': self.username
        }
        return result

    def login(self, token):
        self.last_login = datetime.now()
        self.save()
        result = {
            'avatarURL': 'https://static.shuhelper.cn/' + self.avatar_URL,
            'token': token,
            'name': self.name,
            'nickname': self.nickname,
            'userID': self.id,
            'username': self.username
        }
        return result
Beispiel #8
0
class User(db.Model, UserMixin):
    '''
    The UserAccount class contains user personal informations
    and account settings
    '''
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(100))
    mobile_number = db.Column(db.String(100))
    username = db.Column(db.String(100))
    is_email_verified = db.Column(db.Boolean, default=False)
    _password = db.Column(db.String(255))

    #date
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
    updated_at = db.Column(db.DateTime,
                           default=db.func.current_timestamp(),
                           onupdate=db.func.current_timestamp())
    #delete
    is_deleted = db.Column(db.Boolean, default=False)
    deleted_at = db.Column(db.DateTime)

    roles = db.relationship('Role',
                            secondary=users_roles,
                            backref=db.backref('users'))

    def __unicode__(self):
        return '%s' % str(self.id)

    # ===============================================
    # password
    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, password):
        self._password = bcrypt.generate_password_hash(password).decode(
            'utf-8')
        print(self._password)

    def check_password(self, password):
        if self.password is None:
            return False
        return bcrypt.check_password_hash(self.password, password)

    def to_json(self):
        return dict(created_at=str(self.created_at), email=self.email)

    @property
    def is_admin(self):
        return USER_ROLE.ADMIN in self.roles

    @classmethod
    def is_adminaaa(self):
        aa = self.roles
        print(aa)

    @classmethod
    def authenticate(cls, email=None, password=None):
        if email:
            user = cls.query.filter_by(email=email).first()
        else:
            user = None
        if user:
            authenticated = user.check_password(password)
        else:
            authenticated = False
        return user, authenticated

    # @classmethod
    # def create(cls, email, password, name, mobile_number=None):
    #
    #     account = UserAccount(email=email.lower(),
    #                           mobile_number=mobile_number,
    #                           is_email_verified=True)
    #     account.password = password
    #
    #     db.session.add(account)
    #
    #     user = User(username=name,
    #                 account=account)
    #
    #     db.session.add(account)
    #     db.session.commit()
    #
    #     #signals.user_signup.send('system', user=user)
    #     return user

    def mark_deleted(self):
        if self.is_deleted:
            return
        # delete social oauth, otherwise user can still login via wechat
        # SocialOAuth.objects(user=self).delete()
        self.is_deleted = True
        self.deleted_date = datetime.datetime.utcnow()
        db.session.commit()
Beispiel #9
0
class Herb(BaseModel):
    __tablename__ = "tb_herb"
    bin_hid = db.Column(String(32), primary_key=True)
    s_name = db.Column(String(10), unique=True, nullable=False, comment='药名')
    s_en_name = db.Column(String(100), comment="英文名", default="")

    fk_alias = db.relationship("HerbAlias",
                               backref=db.backref("fk_herb"),
                               cascade="save-update,delete")
    fk_indications = db.relationship("HerbIndications",
                                     backref=db.backref("fk_herb"),
                                     cascade="save-update,delete")
    fk_effect = db.relationship("HerbEffect",
                                backref=db.backref("fk_herb"),
                                cascade="save-update,delete")

    fk_property = db.relationship("DicTableData",
                                  secondary=herb_property_table,
                                  backref=db.backref("fk_herb"))

    s_latin_name = db.Column(String(100), comment="拉丁文名", default="")
    s_abbreviated_name = db.Column(String(20), comment=u"首字母缩写", default="")
    s_usage = db.Column(String(500), comment=u"用法用量", default="")
    s_herb_affiliate = db.Column(String(20), comment="附药的名字", default="")
    s_origin = db.Column(String(200), comment=u"出处", default="")
    s_application = db.Column(String(500), comment=u"应用", default="")
    s_foundation = db.Column(Text, comment=u"基原", default="")
    s_prison = db.Column(Text, comment=u"毒性", default="")
    s_ancient_literature = db.Column(String(500), comment=u"古代文献", default="")
    s_chemical = db.Column(Text, comment=u"化学成分", default="")
    s_discussion = db.Column(db.Text, comment=u"各家论述", default="")
    s_affiliate = db.Column(Text, comment=u"附方", default="")
    s_pharmacological_action = db.Column(Text, comment=u"药理作用", default="")
    s_untoward_effect = db.Column(Text, comment="不良反应", default="")
    s_normal_remark = db.Column(String(500), comment=u"普通备注", default="")
    json_remark = db.Column(JSON, comment="Json备注", default="")

    fk_tcm = db.relationship("TCMSymptom",
                             secondary=herb_tcm_table,
                             backref=db.backref("fk_herb"))

    fk_ingredient = db.relationship("Ingredient",
                                    secondary=herb_gene_table,
                                    backref=db.backref("fk_herb"))

    def __init__(self):
        self.bin_hid = gen_id()

    @staticmethod
    def cls_fk():
        """
        类的外键
        Returns:

        """
        return {
            "four_natures": [],
            "five_tastes": [],
            "floating_and_sinking": [],
            "meridians": [],
            "herb_broad_heading": "",
            "herb_subclass": "",
        }

    def to_dict(self):
        # xing_list = FourNatures.query.filter_by(bin_hid=self.bin_hid).all()

        res = {
            "id": self.bin_hid,
            "s_name": self.s_name,
            "s_en_name": self.s_en_name,
        }

        return res

    def fk_processor_output(self):
        properties = self.fk_property
        property_dict = self.cls_fk()
        for sub_property in properties:
            if isinstance(property_dict[sub_property.fk_dic_type.s_en_name],
                          list):
                property_dict[sub_property.fk_dic_type.s_en_name].append(
                    str(sub_property.id))
            elif isinstance(property_dict[sub_property.fk_dic_type.s_en_name],
                            str):
                property_dict[sub_property.fk_dic_type.s_en_name] = str(
                    sub_property.id)
        return property_dict

    def fk_processor_input(self, fk_data: dict):
        """
        录入数据时,对外键数据进行拆解

        Args:
            fk_data:

        Returns:

        """
        self.fk_property = []
        property_dict = self.cls_fk()
        for k, v in fk_data.items():
            if isinstance(property_dict[k], list):
                if not v:
                    continue
                values = v.split(",")
                for value in values:
                    query_res = DicTableData.query.get(int(value))
                    if query_res:
                        self.fk_property.append(query_res)
                        property_dict[k].append(query_res.s_name)
                    else:
                        raise UnknownValueException("unknown data")
            elif isinstance(property_dict[k], str):
                if not v:
                    continue
                query_res = DicTableData.query.get(int(v))
                if query_res:
                    self.fk_property.append(query_res)
                    property_dict[k] = query_res.s_name
                else:
                    raise UnknownValueException("unknown data")

        for k, v in property_dict.items():
            if isinstance(v, list):
                property_dict[k] = ",".join(v)

        return property_dict

    def to_dict_particular(self):
        property_dict = self.fk_processor_output()
        # for k, v in property_dict.items():
        #     property_dict[k] = ','.join(v)
        res = {
            "id": self.bin_hid,
            "s_name": self.s_name,
            "s_en_name": self.s_en_name,
            "s_latin_name": self.s_latin_name,
            "s_abbreviated_name": self.s_abbreviated_name,
            "s_usage": self.s_usage,
            "s_herb_affiliate": self.s_herb_affiliate,
            "s_origin": self.s_origin,
            "s_application": self.s_application,
            "s_foundation": self.s_foundation,
            "s_prison": self.s_prison,
            "s_ancient_literature": self.s_ancient_literature,
            "s_chemical": self.s_chemical,
            "s_discussion": self.s_discussion,
            "s_affiliate": self.s_affiliate,
            "s_pharmacological_action": self.s_pharmacological_action,
            "s_untoward_effect": self.s_untoward_effect,
            "s_normal_remark": self.s_normal_remark,
            "json_remark": self.json_remark,
            **property_dict,
        }

        return res

    def add(self, data):
        def get_property(cls, pro_list):
            fk_tcmm = []
            for rell in pro_list:
                tmpp = cls.query.filter_by(s_name=rell).first()
                if tmpp:
                    fk_tcmm.append(tmpp)
            return fk_tcmm

        def get_property_1(cls, pro_list):
            """
            针对symmap数据集开发的属性提取方法
            Args:
                cls:
                pro_list:

            Returns:

            """
            fk_tcmm = []
            for rell in pro_list:
                tmpp = cls.query.filter_by(s_mark=rell).first()
                if tmpp:
                    fk_tcmm.append(tmpp)
            return fk_tcmm

        def get_alia(alia_list):
            herb_alia_list = []
            for alia in alia_list:
                herb_alia_list.append(HerbAlias().add({"s_herb_alias": alia}))
            return herb_alia_list

        data["i_status"] = 1
        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value)

        if "s_properties" in data:
            properties = data["s_properties"].split(",")
            self.fk_property = get_property(DicTableData, properties)

        if "rels" in data:
            self.fk_tcm = get_property_1(TCMSymptom, data["rels"].split(","))

            self.fk_ingredient = get_property_1(Ingredient,
                                                data["rels"].split(","))

        if "alias" in data:
            self.fk_alias = get_alia(data["alias"].split(","))

        db.session.add(self)
        neo_data_create_trigger("Herb", data)
        db.session.commit()

    def update(self, data: dict):
        fk_dic = self.cls_fk()
        for key, value in data.items():
            if key in fk_dic:
                fk_dic[key] = data[key]
            if hasattr(self, key) and key != "bin_hid":
                setattr(self, key, value)
        property_dict = self.fk_processor_input(fk_dic)
        data.update(**property_dict)
        db.session.add(self)
        if 's_name' not in data.keys():
            data['s_name'] = self.s_name
        neo_data_update_trigger("Herb", data)
        db.session.commit()

    def extract_json(self, json_req: dict):
        """
        从json文件中提取数据
        Args:
            json_req:

        Returns:

        """
        extract_data = {
            "type": "HERB",
            "s_name": json_req.get("name", ""),
            "s_latin_name": json_req.get("latin_name", ""),
            "s_en_name": json_req.get("en_name", ""),
            "s_origin": json_req.get("origin", ""),
            "s_application": json_req.get("application", ""),
        }
        return {k: v for k, v in extract_data.items() if v}
Beispiel #10
0
class AnalysesLog(BaseModel):
    __tablename__ = "analyses_log"
    id = db.Column(db.BIGINT, primary_key=True, autoincrement=True)
    s_sy_user_id = db.Column(db.Integer, ForeignKey("user.id"))
    s_file_name = db.Column(db.String(100), default="")
    i_rows_number = db.Column(db.INT, default=0)
    j_data = db.Column(db.JSON, default="", comment="记录分析的数据")
    j_remark = db.Column(db.JSON, default="", comment="记录各种参数")
    j_result = db.Column(db.JSON, default="", comment="记录结果")
    s_project_name = db.Column(db.String(50),
                               nullable=False,
                               comment="项目名",
                               default="unnamed")
    s_project_description = db.Column(db.String(1000),
                                      comment="项目描述",
                                      default="")
    f_runtime = db.Column(db.FLOAT, default=-1.0, comment="运行时间")
    i_analysis_type = db.Column(db.SmallInteger, comment="结构化类型")

    i_current_step = db.Column(db.SmallInteger, default=0, comment="目前的进度")
    i_total_step = db.Column(db.SmallInteger, default=4, comment="总进度")

    fk_user = db.relationship("User", backref=db.backref("fk_analyse_log"))

    def __repr__(self):
        return "<s_sy_user_id %r , filename %r>\n" % (self.s_login_name,
                                                      self.file_name)

    def to_dict(self):
        return {
            "create_date_time": self.dt_create_datetime,
            "update_date_time": self.dt_update_datetime,
            "s_project_description": self.s_project_description,
            "login_name": self.fk_user.email,
            "s_project_name": self.s_project_name,
            "status": self.get_mapper()[self.i_status],
            "mark": self.s_mark,
            "analyse_type": self.i_analysis_type,
            "current_step": self.i_current_step,
            "total_step": self.i_total_step,
        }

    def to_dict_particular(self):
        return {
            "create_date_time": self.dt_create_datetime,
            "update_date_time": self.dt_update_datetime,
            "login_name": self.fk_user.email,
            "s_project_description": self.s_project_description,
            "s_project_name": self.s_project_name,
            "status": self.get_mapper()[self.i_status],
            "mark": self.s_mark,
            "runtime": self.f_runtime,
            "data": self.j_data,
            "remark": self.j_remark,
            "analyse_type": self.i_analysis_type,
            "current_step": self.i_current_step,
            "total_step": self.i_total_step,
        }

    @staticmethod
    def get_mapper():
        """
        项目状态映射表
        Returns:

        """
        return ["deleted", "running", "exited", "creating"]

    def add(self, data):
        data["i_status"] = 3
        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value)

        self.fk_user = data["current_user"]
        self.j_data = json.dumps(data["data"], ensure_ascii=False)

        db.session.add(self)
        db.session.commit()

    def stop(self):
        self.update({"i_status": 2})
        db.session.add(self)
        db.session.commit()
Beispiel #11
0
class Order(db.Model, CRUDMixin, TimeMixin):
    __tablename__ = 'room_booking_order'
    id = db.Column(db.UUID(as_uuid=True), default=uuid.uuid4, primary_key=True)
    user_id = db.Column(db.String, db.ForeignKey('user.id'))
    room_id = db.Column(db.UUID, db.ForeignKey('room.id'))
    contact = db.Column(db.String)
    teacher = db.Column(db.String)
    date = db.Column(db.DateTime)
    start = db.Column(db.Integer)
    end = db.Column(db.Integer)
    remark = db.Column(db.String)
    user = db.relationship('User', backref=db.backref('orders', lazy=True))
    members = db.relationship('User',
                              secondary=members,
                              lazy='subquery',
                              backref=db.backref('room_booking_orders',
                                                 lazy=True))

    @property
    def status(self):
        now = datetime.now()
        timedelta = now - self.date
        if timedelta.days > 0:
            return '已结束'
        elif timedelta.days < 0:
            return '未开始'
        elif timedelta.days == 0:
            now = current_day_seconds()
            if self.start <= now and now <= self.end:
                return '已开始'
            if now < self.start:
                return '未开始'
            if now > self.end:
                return '已结束'

    def save(self):
        db.session.add(self)
        db.session.commit()

    def to_json(self):
        return {
            'id': self.id,
            'userID': self.user_id,
            'userName': self.user.name,
            'roomID': self.room_id,
            'room': self.room.name,
            'start': self.start,
            'end': self.end,
            'date': self.date.timestamp(),
            'status': self.status,
            # 'teacher': self.teacher,
            'contact': self.contact,
            'remark': self.remark,
            'members': [member.id for member in self.members]
        }

    @staticmethod
    def from_json(json_post):
        order = Order(
            user_id=json_post['userID'],
            room_id=json_post['roomID'],
            date=datetime.fromtimestamp(json_post['date']),
            start=json_post['start'],
            end=json_post['end'],
            #   teacher=json_post['teacher'],
            contact=json_post['contact'],
            remark=json_post['remark'])
        # order.save()
        return order
Beispiel #12
0
class MMSymptom(BaseModel):
    """
    Manual curation to the UMLS database

    The SMMS file in tabular format includes all descriptive information
     about 961 MM symptoms recorded in SymMap. The details of each column are
      as follows:

    MM_symptom_id:the primary ID of each MM symptom recorded in SymMap.
    MM_symptom_name: the name of each MM symptom.
    MM_symptom_definition: the definition of each MM symptom.
    MeSH_tree_numbers: the hierarchical classification of each MM symptom in
     tree numbers from the MeSH database.
    Alias: multiple aliases separated by a ‘|’ for each MM symptom collected
     from diverse resources.
    UMLS_id: the cross reference of each MM symptom in the UMLS database.
    OMIM_id: the cross reference of each MM symptom in the OMIM database.
    ICD10CM_id: the cross reference of each MM symptom in the ICD (tenth
     clinical modification) database.
    HPO_id: the cross reference of each MM symptom in the HPO database.
    MeSH_id: the cross reference of each MM symptom in the MeSH database.
    The SMMS key file in tabular format includes all the search terms about
     961 MM symptoms recorded in SymMap. The details of each column are as
      follows:

    MM_symptom_id:the primary ID of each MM symptom recorded in SymMap.
    Field_name: the search field of the MM symptom table, including the
     MM_symptom_name, UMLS_id and the alias.
    Field_context:the search terms of all MM symptoms recorded in SymMap.
    """

    __tablename__ = "tb_mm_symptom"
    bin_id = Column(String(32), primary_key=True, comment='id')
    s_name = Column(String(50), default="", comment='名称')
    s_mm_symptom_definition = Column(String(1000), default="", comment='定义')
    s_mm_tree_numbers = Column(String(1000), default="", comment='MM症状在MeSH数据库中的树编号')

    fk_disease = db.relationship(
        "Disease",
        secondary=mm_disease_table,
        backref=db.backref("fk_mm", lazy="dynamic"),
    )

    def __init__(self):
        self.bin_id = gen_id()

    def add(self, data):
        data["i_status"] = 1

        fk_disease = []
        for rel in data["rels"].split(","):
            tmp = Disease.query.filter_by(s_mark=rel).first()
            if tmp:
                fk_disease.append(tmp)
        if fk_disease:
            self.fk_disease = fk_disease

        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value)
        db.session.add(self)
        db.session.commit()

    def to_dict(self):
        return {
            "id": self.bin_id,
            "s_name": self.s_name,
            "s_mm_symptom_definition": self.s_mm_symptom_definition,
            "s_mm_tree_numbers": self.s_mm_tree_numbers,
            "disease": ",".join([foo.s_name for foo in self.fk_disease]),
        }

    def to_dict_particular(self):
        return {
            "id": self.bin_id,
            "s_name": self.s_name,
            "s_mm_symptom_definition": self.s_mm_symptom_definition,
            "s_mm_tree_numbers": self.s_mm_tree_numbers,
            "disease": ",".join([foo.s_name for foo in self.fk_disease]),
        }
Beispiel #13
0
class TCMSymptom(BaseModel):
    """
    Chinese pharmacopoeia (2015)

    The SMTS file in tabular format includes all descriptive information about
     1,717 TCM symptoms recorded in SymMap. The details of each column are as
      follows:

    TCM_symptom_id: the primary ID of each TCM symptom recorded in SymMap.
    TCM_symptom_name: the name of TCM symptoms in Chinese.
    Symptom_pinyin_name: the name of TCM symptoms in Pinyin.
    Symptom_definition: the definition of TCM symptoms using the terms from
     traditional Chinese medicine.
    Symptom_locus: the locus of TCM symptoms using the terms from traditional
     Chinese medicine.
    Symptom_property: the property of TCM symptoms using the terms from
     traditional Chinese medicine.
    The SMTS key file in tabular format includes all the search terms about
     1,717 TCM symptoms recorded in SymMap. The details of each column are
      as follows:

    TCM_symptom_id: the primary ID of each TCM symptom recorded in SymMap.
    Field_name: the search field of the TCM symptom table, including the
     TCM_symptom_name and the symptom_pinyin_name.
    Field_context:the search terms of all TCM symptoms recorded in SymMap.
    """

    __tablename__ = "tb_tcm_symptom"
    bin_id = Column(String(32), primary_key=True, comment='id')
    s_name = Column(String(50), default="", comment='症状名称')
    s_pinyin_name = Column(String(50), default="", comment='汉语拼音')
    s_symptom_definition = Column(String(1000), default="", comment='定义')
    s_symptom_locus = Column(String(50), default="", comment="症状病位")
    s_symptom_property = Column(String(100), default="", comment='症状属性')

    fk_mm = db.relationship(
        "MMSymptom",
        secondary=tcm_mm_table,
        backref=db.backref("fk_tcm", lazy="dynamic"),
    )

    def __init__(self):
        self.bin_id = gen_id()

    def add(self, data):
        data["i_status"] = 1

        fk_mm = []
        for rel in data["rels"].split(","):
            tmp = MMSymptom.query.filter_by(s_mark=rel).first()
            if tmp:
                fk_mm.append(tmp)
        if fk_mm:
            self.fk_mm = fk_mm

        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value)
        db.session.add(self)
        db.session.commit()

    def to_dict(self):
        return {
            "id": self.bin_id,
            "s_name": self.s_name,
            "s_pinyin_name": self.s_pinyin_name,
            "s_symptom_definition": self.s_symptom_definition,
            "s_symptom_locus": self.s_symptom_locus,
            "s_symptom_property": self.s_symptom_property,
            "mm": ",".join([foo.s_name for foo in self.fk_mm]),
        }

    def to_dict_particular(self):
        return {
            "id": self.bin_id,
            "s_name": self.s_name,
            "s_pinyin_name": self.s_pinyin_name,
            "s_symptom_definition": self.s_symptom_definition,
            "s_symptom_locus": self.s_symptom_locus,
            "s_symptom_property": self.s_symptom_property,
            "mm": ",".join([foo.s_name for foo in self.fk_mm]),
        }
Beispiel #14
0
class LostNFoundPost(db.Model, CRUDMixin, TimeMixin):
    id = db.Column(db.UUID(as_uuid=True), default=uuid.uuid4, primary_key=True)
    author_id = db.Column(db.String, db.ForeignKey('user.id'))
    type = db.Column(db.String)  # lost or found
    title = db.Column(db.String)
    category = db.Column(db.String)
    location_type = db.Column(db.String)
    latitude = db.Column(db.Float)
    longitude = db.Column(db.Float)
    content = db.Column(db.String)
    img_URLs = db.Column(postgresql.ARRAY(db.String, dimensions=1))
    address = db.Column(db.String)
    occurred_time = db.Column(db.DateTime, default=datetime.now)
    contact = db.Column(db.String)
    is_found = db.Column(db.Boolean, default=False)
    site = db.Column(db.String)
    hit = db.Column(db.Integer, default=0)
    lighten_time = db.Column(db.DateTime, default=datetime.now)
    lighten_count = db.Column(db.Integer, default=0)
    author = db.relationship('User',
                             backref=db.backref('lost_n_found_posts',
                                                lazy=True))

    @classmethod
    def from_json(cls, json_post):
        post = cls(
            type=json_post['type'],
            author_id=json_post['authorID'],
            title=json_post['title'],
            content=json_post['content'],
            latitude=json_post['latitude'],
            longitude=json_post['longitude'],
            img_URLs=json_post['imgURLs'],
            address=json_post['address'],
            category=json_post['category'],
            site=json_post['site'],
            # occurred_time = datetime.fromtimestamp(json_post['occurredTime']),
            contact=json_post['contact'])
        return post

    def to_json(self):
        return {
            'id': self.id,
            'type': self.type,
            'authorID': self.author_id,
            'authorName': self.author.username,
            'authorAvatar': self.author.avatar_URL,
            'category': self.category,
            'title': self.title,
            'content': self.content,
            'latitude': self.latitude,
            'longitude': self.longitude,
            'imgURLs': self.img_URLs,
            'address': self.address,
            'occurredTime': self.occurred_time.timestamp(),
            'contact': self.contact,
            'isFound': self.is_found,
            'site': self.site,
            'lightenTime': self.lighten_time,
            'lightenCount': self.lighten_count
        }

    def change_found_status(self, is_founded):
        self.is_found = is_founded
        self.save()

    def lighten(self):
        self.lighten_time = datetime.now()
        self.lighten_count += 1
        self.save()
Beispiel #15
0
class Ingredient(BaseModel):
    """
    Integration of TCMID, TCMSP and TCM-ID database

    The SMIT file in tabular format includes all descriptive information about
     19,595 ingredients recorded in SymMap. The details of each column are
      as follows:

    Ingredient_id:the primary ID of each ingredient recorded in SymMap.
    Molecule_name:the common name of each ingredient. Generally, we selected
     the first name appeared in the PubChem database.
    Molecule_formula: the molecule formula for each ingredient.
    Molecule_weight: the molecule weight for each ingredient.
    OB_score:the oral bioavailability score for each ingredient.
    Alias: multiple aliases separated by a ‘|’ for each ingredient collected
     from diverse resources.
    PubChem_id: the cross reference of each ingredient in the PubChem database.
    CAS_id: the cross reference of each ingredient in the CAS database.
    TCMID_id: the cross reference of each ingredient in the TCMID database.
    TCM-ID_id: the cross reference of each ingredient in the TCM-ID database.
    TCMSP_id: the cross reference of each ingredient in the TCMSP database.
    The SMIT key file in tabular format includes all the search terms about
     19,595 ingredients recorded in SymMap. The details of each column are
      as follows:

    Ingredient_id:the primary ID of each ingredient recorded in SymMap.
    Field_name: the search field of the ingredient table, including the
     molecule_name, alias and the CAS_id.
    Field_context:the search terms of all ingredient recorded in SymMap.
    """

    __tablename__ = "tb_ingredient"
    bin_id = Column(String(32), primary_key=True, comment='id')
    s_name = Column(String(500), default="", comment='成分名称')
    s_molecule_formula = Column(String(255), default="", comment='分子式')
    f_molecule_weight = Column(Float, default=-1.0, comment='分子权重')
    f_ob_score = Column(Float, default=-1.0, comment='每种成分的口服生物利用度得分')
    s_alias = Column(Text, default="", comment='别名')

    fk_target = db.relationship(
        "Target",
        secondary=target_gene_table,
        backref=db.backref("fk_target_ingredient", lazy="dynamic"),
    )

    def __init__(self):
        self.bin_id = gen_id()

    def add(self, data):
        data["i_status"] = 1
        data["f_ob_score"] = float(
            data["f_ob_score"]) if data["f_ob_score"] else -1.0
        data["f_molecule_weight"] = (float(data["f_molecule_weight"])
                                     if data["f_molecule_weight"] else -1.0)

        fk_target = []
        for rel in data["rels"].split(","):
            tmp = Target.query.filter_by(s_mark=rel).first()
            if tmp:
                fk_target.append(tmp)
        if fk_target:
            self.fk_target = fk_target

        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value)
        db.session.add(self)
        db.session.commit()

    def to_dict(self):
        return {
            "id": self.bin_id,
            "s_name": self.s_name,
            "s_molecule_formula": self.s_molecule_formula,
            "f_molecule_weight": self.f_molecule_weight,
            "f_ob_score": self.f_ob_score,
            "s_alias": self.s_alias,
            "target": ",".join([foo.s_name for foo in self.fk_target]),
        }

    def to_dict_particular(self):
        return {
            "id": self.bin_id,
            "s_name": self.s_name,
            "s_molecule_formula": self.s_molecule_formula,
            "f_molecule_weight": self.f_molecule_weight,
            "f_ob_score": self.f_ob_score,
            "s_alias": self.s_alias,
            "target": ",".join([foo.s_name for foo in self.fk_target]),
        }
Beispiel #16
0
class Target(BaseModel):
    """
    Integration of HIT, TCMSP, HPO, DrugBank and NCBI database

    The SMTT file in tabular format includes all descriptive information about 4,302 targets recorded in SymMap. The details of each column are as follows:

    Target_id:the primary ID of each target recorded in SymMap.
    Gene_symbol: the gene symbol of each target.
    Chromosome: the chromosome number in which each target located.
    Gene_name: the gene name of each target.
    Protein_name: the protein name of each target.
    Alias: multiple aliases separated by a ‘|’ for each target collected
     from diverse resources.
    HIT_id: the cross reference of each target in the HIT database.
    TCMSP_id: the cross reference of each target in the TCMSP database.
    Ensembl_id: the cross reference of each target in the Ensembl database.
    NCBI_id: the cross reference of each target in the NCBI database.
    HGNC_id: the cross reference of each target in the HGNC database.
    Vega_id: the cross reference of each target in the Vega database.
    GenBank_Gene_id: the cross reference of each target in the GenBank_Gene
     database.
    GenBank_Protein_id: the cross reference of each target in the
     GenBank_Protein database.
    Uniprot_id: the cross reference of each target in the Uniprot database.
    PDB_id: the cross reference of each target in the PDB database.
    OMIM_id: the cross reference of each target in the OMIM database.
    miRBase_id: the cross reference of each target in the miRBase database.
    IMGT/GENE-DB_id: the cross reference of each target in the IMGT/GENE-DB
     database.
    The SMTT key file in tabular format includes all the search terms about
     4,302 targets recorded in SymMap. The details of each column are
      as follows:

    Target_id :the primary ID of each target recorded in SymMap.
    Field_name: the search field of the target table, including the
     gene_symbol, gene_name, protein_name, alias and the Ensembl_id.
    Field_context:the search terms of all target recorded in SymMap.
    """

    __tablename__ = "tb_target"
    bin_id = Column(String(32), primary_key=True, comment='id')
    s_gene_symbol = Column(String(50), default="", comment='基因符号')
    s_chromosome = Column(String(20), default="", comment='染色体')
    s_name = Column(String(500), default="", comment='靶点名称')
    s_protein_name = Column(String(500), default="", comment='蛋白质名称')

    fk_disease = db.relationship(
        "Disease",
        secondary=target_disease_table,
        backref=db.backref("fk_target", lazy="dynamic"),
    )

    def add(self, data):
        data["i_status"] = 1
        fk_disease = []
        for rel in data["rels"].split(","):
            tmp = Disease.query.filter_by(s_mark=rel).first()
            if tmp:
                fk_disease.append(tmp)
        if fk_disease:
            self.fk_disease = fk_disease
        for key, value in data.items():
            if hasattr(self, key):
                setattr(self, key, value)
        db.session.add(self)
        db.session.commit()

    def __init__(self):
        self.bin_id = gen_id()

    def to_dict(self):
        return {
            "id": self.bin_id,
            "s_gene_symbol": self.s_gene_symbol,
            "s_chromosome": self.s_chromosome,
            "s_name": self.s_name,
            "s_protein_name": self.s_protein_name,
            "disease": ",".join([foo.s_name for foo in self.fk_disease]),
        }

    def to_dict_particular(self):
        return {
            "id": self.bin_id,
            "s_gene_symbol": self.s_gene_symbol,
            "s_chromosome": self.s_chromosome,
            "s_name": self.s_name,
            "s_protein_name": self.s_protein_name,
            "disease": ",".join([foo.s_name for foo in self.fk_disease]),
        }