Ejemplo n.º 1
0
class Mvsi(BasicModel):
    """
    机动车销售发票
    """
    __tablename__ = 'MVSI_OCR'

    ocr_file_id = db.Column(db.String(length=64),
                            db.ForeignKey('OCR_FILE.ID'),
                            name='OCR_FILE_ID',
                            nullable=False,
                            index=True,
                            comment='OCR流程ID')
    code = db.Column(db.String(length=20), name='CODE', comment='发票代码')
    number = db.Column(db.String(length=20), name='NUMBER', comment='发票号码')
    issue_date = db.Column(db.DateTime, name='ISSUE_DATE', comment='开票日期')
    machine_printed_code = db.Column(db.String(length=20),
                                     name='MACHINE_PRINTED_CODE',
                                     comment='机打代码')
    machine_printed_number = db.Column(db.String(length=20),
                                       name='MACHINE_PRINTED_NUMBER',
                                       comment='机打号码')
    machine_number = db.Column(db.String(length=20),
                               name='MACHINE_NUMBER',
                               comment='机器编号')
    fiscal_code = db.Column(db.String(length=190),
                            name='FISCAL_CODE',
                            comment='税控码')
    buyer_name = db.Column(db.String(length=20),
                           name='BUYER_NAME',
                           comment='购买方名称')
    buyer_organization_number = db.Column(db.String(length=30),
                                          name='BUYER_ORGANIZATION_NAMBER',
                                          comment='购买方身份证号码/组织机构代码')
    buyer_id = db.Column(db.String(length=20),
                         name='BUYER_ID',
                         comment='购买方纳税人识别号')
    seller_name = db.Column(db.Text, name='SELLER_NAME', comment='销售方名称')
    seller_phone = db.Column(db.String(length=20),
                             name='SELLER_PHONE',
                             comment='销售方电话')
    seller_id = db.Column(db.String(length=20),
                          name='SELLER_ID',
                          comment='销售方纳税人识别号')
    seller_account = db.Column(db.String(length=64),
                               name='SELLER_ACCOUNT',
                               comment='销售方账号')
    seller_address = db.Column(db.Text, name='SELLER_ADDRESS', comment='销售方地址')
    seller_bank = db.Column(db.Text, name='SELLER_BANK', comment='销售方开户行')
    vehicle_type = db.Column(db.Text, name='VEHICLE_TYPE', comment='多用途乘用车')
    brand_model = db.Column(db.Text, name='BRAND_MODEL', comment='厂牌型号')
    manufacturing_location = db.Column(db.String(length=225),
                                       name='MANUFACTURING_LOCATION',
                                       comment='产地')
    quality_certificate = db.Column(db.String(length=20),
                                    name='QUALITY_CERTIFICATE',
                                    comment='合格证号')
    import_certificate = db.Column(db.String(length=18),
                                   name='IMPORT_CERTIFICATE',
                                   comment='进口证明书号')
    inspection_number = db.Column(db.String(length=20),
                                  name='INSPECTION_NUMBER',
                                  comment='商检单号')
    engine_number = db.Column(db.String(length=20),
                              name='ENGINE_NUMBER',
                              comment='发动机号码')
    vehicle_identification_number = db.Column(
        db.String(length=20),
        name='VEHICLE_IDENTIFICATION_NUMBER',
        comment='车架号码')
    tonnage = db.Column(db.String(length=10), name='TONNAGE', comment='吨位')
    seating_capacity = db.Column(db.String(length=10),
                                 name='SEATING_CAPACITY',
                                 comment='限乘人数')
    tax_authority = db.Column(db.Text, name='TAX_AUTHORITY', comment='主管税务机关')
    tax_authority_code = db.Column(db.String(length=20),
                                   name='TAX_AUTHORITY_CODE',
                                   comment='主管税务机关代码')
    tax_payment_receipt = db.Column(db.String(length=18),
                                    name='TAX_PAYMENT_RECEIPT',
                                    comment='完税凭证号码')
    tax_rate = db.Column(db.String(length=6),
                         name='TAX_RATE',
                         comment='增值税税率或征收率')
    tax = db.Column(db.Numeric(precision=20, scale=2, asdecimal=False),
                    name='TAX',
                    nullable=False,
                    default=0.00,
                    comment='增值税税额')
    tax_exclusive_price = db.Column(db.Numeric(precision=20,
                                               scale=2,
                                               asdecimal=False),
                                    name='TAX_EXCLUSIVE_PRICE',
                                    nullable=False,
                                    default=0.00,
                                    comment='增值税税额')
    total = db.Column(db.Numeric(precision=20, scale=2, asdecimal=False),
                      name='TOTAL',
                      nullable=False,
                      default=0.00,
                      comment='价税合计')
    total_chinese = db.Column(db.Text, name='TOTAL_CHINESE', comment='价税合计大写')

    def __init__(self, **kwargs):
        super(self.__class__, self).__init__(**kwargs)

    def dao_add(self, ocrFile, file_model, file_path):
        """
        数据入库
        :param ocrFile:
        :param file_model
        :param file_path: 文件路径
        :return:
        """
        super().dao_create()
        with db.auto_commit_db(False,
                               False,
                               error_call=FileUtil.del_file,
                               file_path=file_path) as s:
            # 文件入库
            file_model.dao_init_file(file_path,
                                     id=file_model.id,
                                     file_name=ocrFile.file_data.file_name,
                                     nested=True)

            ocrFile.file_id = file_model.id
            ocrFile.dao_add(nested=True)

            self.ocr_file_id = ocrFile.id
            s.add(self)
Ejemplo n.º 2
0
class UserModel(db.Model):
    """
    A user Model class
    """

    __tablename__ = "user"

    ROLE = OrderedDict([
        ('member', 'Member'),
        ('admin', 'Admin'),
    ])

    id = db.Column(db.String, primary_key=True)
    role = db.Column(db.Enum(*ROLE, name='role_types', native_enum=False),
                     index=True,
                     nullable=False,
                     server_default='member')
    disabled = db.Column(db.Boolean, default=False)
    password = db.Column(db.String(), nullable=True)
    email = db.Column(db.String(80), nullable=True, unique=True)

    created_on = db.Column(AwareDateTime(),
                           default=tzware_datetime,
                           nullable=False)
    updated_on = db.Column(AwareDateTime(),
                           default=tzware_datetime,
                           onupdate=tzware_datetime)

    # Activity tracking.
    sign_in_count = db.Column(db.Integer, nullable=False, default=0)
    current_sign_in_on = db.Column(AwareDateTime())
    current_sign_in_ip = db.Column(db.String(45))
    last_sign_in_on = db.Column(AwareDateTime())
    last_sign_in_ip = db.Column(db.String(45))
    tracking = db.relationship("TrackingModel",
                               lazy="dynamic",
                               cascade="all, delete-orphan")
    movies = db.relationship("MovieModel",
                             lazy="dynamic",
                             cascade="all, delete-orphan")

    @staticmethod
    def create_user(email: str, password: str) -> "UserModel":
        """
        create a user and return a user
        Returns:

        """
        user = UserModel()
        if email is None or email == "":
            raise ValueError("email must be provided")
        user.email = normalize_email(email)
        user.password = UserModel.encrypt_password(password)
        user.id = uuid4().hex
        user.created_on = datetime.datetime.now(pytz.utc)

        return user

    @classmethod
    def find_by_email(cls, email: str) -> "UserModel":
        """
        Find a user by email
        Args:
            email: email value to use in searching for user

        Returns:
            UserModel class object
        """
        return cls.query.filter_by(email=email).first()

    @classmethod
    def find_by_id(cls, _id: int) -> "UserModel":
        """
        Find a user by id
        Args:
            _id: user id to use in searching for a user

        Returns:
            UserModel class object
        """
        return cls.query.filter_by(id=_id).first()

    @staticmethod
    def create_superuser(email: str, password: str) -> "UserModel":
        """
        create a user and return a user
        Returns:

        """
        user = UserModel()
        if email is None or email == "":
            raise ValueError("email must be provided")
        user.email = normalize_email(email)
        user.password = UserModel.encrypt_password(password)
        user.role = 'Admin'

        return user

    def check_password(self, password: str) -> bool:
        """
        Ensure a user is authenticated, checking their password.
        Args:
            password: plain password to be checked with

        Returns:
           bool
        """
        return check_password_hash(self.password, password)

    @staticmethod
    def encrypt_password(password: str) -> str:
        """
        Hash a plaintext string using PBKDF2. This is good enough according
        to the NIST (National Institute of Standards and Technology).

        In other words while bcrypt might be superior in practice, if you use
        PBKDF2 properly (which we are), then your passwords are safe.
        Args:
            password: plain password to be checked with

        Returns:
            str
        """
        return generate_password_hash(password)

    def update_activity_tracking(self, ip_address: str):
        """
        Update various fields on the user that's related to meta data on their
        account, such as the sign in count and ip address, etc..
        Args:
            ip_address:

        Returns:

        """
        self.sign_in_count += 1

        self.last_sign_in_on = self.current_sign_in_on
        self.last_sign_in_ip = self.current_sign_in_ip

        self.current_sign_in_on = datetime.datetime.now(pytz.utc)
        self.current_sign_in_ip = ip_address

        self.save()

    def save(self) -> None:
        """
        save user to db
        Returns:

        """
        db.session.add(self)
        db.session.commit()
Ejemplo n.º 3
0
class Author(db.Model):
    __tablename__ = 'author'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False, unique=True)
    comments = db.relationship("Comment", backref="author")
Ejemplo n.º 4
0
class Classifier(Model, CRUDMixin):
    __tablename__   = "classifiers"

    id              = Column(db.Integer, primary_key = True)
    name            = Column(db.String(250))

    owner_id = Column(db.Integer, db.ForeignKey("users.id"))

    # many to many
    videos = relationship("Video", secondary=video_classifier_association_table, backref='classifiers')

    # it's stored as string array, since there is no reference need
    labels = Column(db.String(250))
    # one to many
    children = relationship("Classifier")

    parent_id = Column(db.Integer, db.ForeignKey("classifiers.id"))

    # training images
    training_image_list_file_path  = Column(db.String(550))
    training_label_list_file_path  = Column(db.String(550))
    training_label_name_file_path  = Column(db.String(550))
    epoch   = Column(db.Integer, default=0)

    # a string to indicate the network type: ['Fast_RCNN', 'mxnet']
    network_type  = Column(db.String(250))

    # the name of model, specified by the user
    model_name  = Column(db.String(250))

    # training status: [(0, none), (1, waiting), (2, training), (3, finished)]
    task_id   = Column(db.String(250))
    # the type of the task: [train, test]
    task_type   = Column(db.String(250))
    training_status   = Column(db.Integer, default=0)
    training_start_time   = Column(db.BigInteger)
    training_end_time   = Column(db.BigInteger)

    # many to many
    evaluation_sets = relationship("EvaluationSet", secondary=classifier_evaluation_association_table, back_populates='classifiers')

    container_id   = Column(db.String(250))
    image_id   = Column(db.String(250))
Ejemplo n.º 5
0
class Article(db.Model):
    __tablename__ = 'article'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
Ejemplo n.º 6
0
class Payment(db.Model):
    __tablename__ = 'payments'
    paymentID = db.Column(db.Integer(), primary_key=True)
    type = db.Column(db.String())
Ejemplo n.º 7
0
class Interval(db.Model):
    __tablename__ = 'interval'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True, nullable=False)
Ejemplo n.º 8
0
class Recipe(db.Model):
    __tablename__ = 'recipe'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(200))
    num_of_servings = db.Column(db.Integer)
    cook_time = db.Column(db.Integer)
    ingredients = db.Column(db.String(1000))
    directions = db.Column(db.String(1000))
    is_publish = db.Column(db.Boolean(), default=False)
    cover_image = db.Column(db.String(100), default=None)

    created_at = db.Column(db.DateTime(),
                           nullable=False,
                           server_default=db.func.now())
    updated_at = db.Column(db.DateTime(),
                           nullable=False,
                           server_default=db.func.now(),
                           onupdate=db.func.now())

    user_id = db.Column(db.Integer(), db.ForeignKey("user.id"))

    @classmethod
    def get_all_published(cls, q, page, per_page, sort, order):

        keyword = '%{keyword}%'.format(keyword=q)

        if order == 'asc':
            sort_logic = asc(getattr(cls, sort))
        else:
            sort_logic = desc(getattr(cls, sort))

        return cls.query.filter(or_(cls.name.ilike(keyword),
                                    cls.description.ilike(keyword),
                                    cls.ingredients.ilike(keyword)),
                                cls.is_publish.is_(True)). \
            order_by(sort_logic).paginate(page=page, per_page=per_page)

    @classmethod
    def get_all_by_user(cls, user_id, page, per_page, visibility='public'):

        query = cls.query.filter_by(user_id=user_id)

        if visibility == 'public':
            query = cls.query.filter_by(user_id=user_id, is_publish=True)
        elif visibility == 'private':
            query = cls.query.filter_by(user_id=user_id, is_publish=False)

        return query.order_by(desc(cls.created_at)).paginate(page=page,
                                                             per_page=per_page)

    @classmethod
    def get_by_id(cls, recipe_id):
        return cls.query.filter_by(id=recipe_id).first()

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

    def delete(self):
        db.session.delete(self)
        db.session.commit()
Ejemplo n.º 9
0
class User(db.Model, UserMixin):

    __tablename__ = 'users'

    #id = Column(db.Integer, primary_key=True)
    id = Column(UUIDType(binary=False), primary_key=True)
    name = Column(db.String(STRING_LEN), nullable=False, unique=True)
    email = Column(db.String(STRING_LEN), nullable=False, unique=True)
    phone = Column(db.String(STRING_LEN), nullable=False, default="")
    url = Column(db.String(STRING_LEN), nullable=False, default="")
    deposit = Column(db.Numeric, nullable=False, default=0.0)
    location = Column(db.String(STRING_LEN), nullable=False, default="")
    bio = Column(db.Text, default="")
    activation_key = Column(db.String(STRING_LEN))
    create_at = Column(db.DateTime, nullable=False, default=get_current_time)
    update_at = Column(db.DateTime)

    avatar = Column(db.String(STRING_LEN))

    _password = Column('password', db.String(200), nullable=False, default="")

    def _get_password(self):
        return self._password

    def _set_password(self, password):
        self._password = generate_password_hash(password)

    # Hide password encryption by exposing password field only.
    password = db.synonym('_password',
                          descriptor=property(_get_password, _set_password))

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

    _sex = Column('sex', db.Integer, nullable=False, default=1)

    def _get_sex(self):
        return SEX_TYPES.get(self.sex)

    def _set_sex(self, sex):
        self._sex = sex

    sex = db.synonym('_sex', descriptor=property(_get_sex, _set_sex))

    # ================================================================
    role_code = Column(db.SmallInteger, default=USER, nullable=False)

    @property
    def role(self):
        return USER_ROLE[self.role_code]

    def is_admin(self):
        return self.role_code == ADMIN

    # ================================================================
    # One-to-many relationship between users and user_statuses.
    status_code = Column(db.SmallInteger, nullable=False, default=INACTIVE)

    @property
    def status(self):
        return USER_STATUS[self.status_code]

    # ================================================================
    # Class methods
    @classmethod
    def get_count(cls):
        count_q = cls.query.statement.with_only_columns([func.count()
                                                         ]).order_by(None)
        count = db.session.execute(count_q).scalar()
        return count

    @classmethod
    def authenticate(cls, login, password):
        user = cls.query.filter(db.or_(User.name == login,
                                       User.email == login)).first()

        if user:
            authenticated = user.check_password(password)
        else:
            authenticated = False

        return user, authenticated

    @classmethod
    def search(cls, keywords):
        criteria = []
        for keyword in keywords.split():
            keyword = '%' + keyword + '%'
            criteria.append(
                db.or_(
                    User.name.ilike(keyword),
                    User.email.ilike(keyword),
                ))
        q = reduce(db.and_, criteria)
        return cls.query.filter(q)

    @classmethod
    def get_by_id(cls, user_id):
        return cls.query.filter_by(id=user_id).first_or_404()

    def check_name(self, name):
        return User.query.filter(
            db.and_(User.name == name, User.email != self.id)).count() == 0

    @staticmethod
    def get_or_create(me):
        user = User.query.filter_by(name=me['login']).first()
        if user is None:
            user = User(id=uuid.uuid4(),
                        name=me['login'],
                        password=session['token'],
                        email=me['email'],
                        avatar=me['avatar_url'],
                        location=me['location'],
                        bio=me['bio'])
            db.session.add(user)
            db.session.commit()
        return user
Ejemplo n.º 10
0
class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(500), nullable=False)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow(), index=True)
    author = db.relationship("User", back_populates="messages")
    author_id = db.Column(db.Integer, db.ForeignKey("user.id"))
Ejemplo n.º 11
0
from extensions import db

user_interest = db.Table(
    'user_interest',
    db.Column('user_address',
              db.String(50),
              db.ForeignKey('user.email'),
              primary_key=True),
    db.Column('interest_id',
              db.Integer,
              db.ForeignKey('interest.id'),
              primary_key=True))
Ejemplo n.º 12
0
class Nodedb(db.Model):

    __tablename__ = 'nodedb'

    def __repr__(self):
        return '<node %r>' % self.node_name

    #id = Column(db.Integer, primary_key=True)
    id = Column(UUIDType(binary=False), default=uuid.uuid4, primary_key=True)
    node_name = Column(db.String(STRING_LEN),
                       nullable=False,
                       unique=True,
                       index=True,
                       info={
                           'verbose_name': u'Node名',
                       })
    #node_ip = Column(db.String(STRING_LEN), nullable=False,
    #                 unique=False, info={'verbose_name': u'Node IP', })
    node_ip = Column(JSONType(10000), nullable=False, default='')
    node_port = Column(db.String(STRING_LEN),
                       nullable=False,
                       default="",
                       info={
                           'verbose_name': u'Node 端口',
                       })
    username = Column(db.String(STRING_LEN), nullable=False, default='salt')
    password = Column(db.String(STRING_LEN), nullable=False, default='sugar')
    #location = Column(db.String(STRING_LEN), nullable=False, default="")
    #location_id = Column(UUIDType(binary=False), db.ForeignKey(
    #    'location.id'), nullable=False, default="", info={'verbose_name': u'提供商', })
    #location = db.relationship('Location', backref='nodes')
    bio = Column(db.Text, default="", info={
        'verbose_name': u'备注',
    })
    ssh_key = Column(db.String(STRING_LEN))
    create_at = Column(db.DateTime,
                       nullable=False,
                       default=get_current_time,
                       info={
                           'verbose_name': u'创建时间',
                       })
    update_at = Column(db.DateTime, info={
        'verbose_name': u'更新时间',
    })
    master_id = Column(UUIDType(binary=False),
                       db.ForeignKey('masterdb.id'),
                       nullable=False,
                       default="",
                       info={
                           'verbose_name': u'Master',
                       })
    master = db.relationship('Masterdb', backref='nodes')
    avatar = Column(db.String(STRING_LEN), nullable=False, default='')
    minion_data = Column(JSONType(10000), nullable=False, default='')
    os = Column(db.String(STRING_LEN), nullable=False, default='')
    kenel = Column(db.String(STRING_LEN), nullable=False, default='')
    core = Column(db.Integer, nullable=False, default=0)
    cpu = Column(db.String(STRING_LEN), nullable=False, default='')
    mem = Column(db.String(STRING_LEN), nullable=False, default='')
    host = Column(db.String(STRING_LEN), nullable=False, default='')
    status = Column(db.String(STRING_LEN), nullable=False, default='')

    @classmethod
    def get_nodes(cls):
        q = cls.query.with_entities(cls.node_name).all()
        return q

    @classmethod
    def get_count(cls):
        count_q = cls.query.statement.with_only_columns([func.count()
                                                         ]).order_by(None)
        count = db.session.execute(count_q).scalar()
        return count

    @classmethod
    def get_list(cls, page=1):
        q = cls.query.order_by(cls.update_at.desc())
        return cls.paginate(query=q, page=page)

    @staticmethod
    def paginate(query, page, per_page=20, error_out=False):
        if error_out and page < 1:
            abort(404)
        items = query.limit(per_page).offset((page - 1) * per_page).all()
        if not items and page != 1 and error_out:
            abort(404)

        # No need to count if we're on the first page and there are fewer
        # items than we expected.
        if page == 1 and len(items) < per_page:
            total = len(items)
        else:
            total = query.order_by(None).count()

        return Pagination(query, page, per_page, total, items)
Ejemplo n.º 13
0
class Masterdb(db.Model):
    __tablename__ = 'masterdb'

    def __repr__(self):
        return '<Master APi %r>' % self.master_name

    #id = Column(db.Integer, primary_key=True)
    id = Column(UUIDType(binary=False), primary_key=True)
    master_name = Column(db.String(STRING_LEN),
                         nullable=False,
                         unique=True,
                         index=True,
                         info={
                             'verbose_name': u'主机名',
                         })
    master_ip = Column(db.String(STRING_LEN),
                       nullable=False,
                       unique=False,
                       info={
                           'verbose_name': u'主机IP',
                       })
    master_port = Column(db.String(STRING_LEN),
                         nullable=False,
                         default="",
                         info={
                             'verbose_name': u'主机端口',
                         })
    master_api_url = Column(db.String(STRING_LEN),
                            nullable=False,
                            default="",
                            info={
                                'verbose_name': u'主机API地址',
                            })
    master_api_port = Column(db.Integer,
                             nullable=False,
                             default=0,
                             info={
                                 'verbose_name': u'主机API端口',
                             })
    username = Column(db.String(STRING_LEN), nullable=False, default='salt')
    password = Column(db.String(STRING_LEN), nullable=False, default='sugar')
    #location = Column(db.String(STRING_LEN), nullable=False, default="")
    location_id = Column(UUIDType(binary=False),
                         db.ForeignKey('location.id'),
                         nullable=False,
                         default="",
                         info={
                             'verbose_name': u'提供商',
                         })
    location = db.relationship('Location', backref='masters')
    bio = Column(db.Text, default="", info={
        'verbose_name': u'备注',
    })
    ssh_key = Column(db.String(STRING_LEN))
    create_at = Column(db.DateTime,
                       nullable=False,
                       default=get_current_time,
                       info={
                           'verbose_name': u'创建时间',
                       })
    update_at = Column(db.DateTime, info={
        'verbose_name': u'更新时间',
    })
    operator = Column(UUIDType(binary=False),
                      nullable=True,
                      info={
                          'verbose_name': u'Master',
                      })
    avatar = Column(db.String(STRING_LEN), nullable=False, default='')
    token = Column(db.String(STRING_LEN), nullable=False, default='')
    token_expire = Column(db.Float, nullable=False, default=0.0)
    minion_data = Column(JSONType(1000), nullable=False, default='')

    def ret_api(self):
        #return self.master_api_url + ":" + str(self.master_api_port)
        return self.master_api_url

    @classmethod
    def get_count(cls):
        count_q = cls.query.statement.with_only_columns([func.count()
                                                         ]).order_by(None)
        count = db.session.execute(count_q).scalar()
        return count

    @classmethod
    def get_list(cls, page=1):
        q = cls.query.order_by(cls.update_at.desc())
        return cls.paginate(query=q, page=page)

    @staticmethod
    def paginate(query, page, per_page=20, error_out=False):
        if error_out and page < 1:
            abort(404)
        items = query.limit(per_page).offset((page - 1) * per_page).all()
        if not items and page != 1 and error_out:
            abort(404)

        # No need to count if we're on the first page and there are fewer
        # items than we expected.
        if page == 1 and len(items) < per_page:
            total = len(items)
        else:
            total = query.order_by(None).count()

        return Pagination(query, page, per_page, total, items)
Ejemplo n.º 14
0
class RegisteredUser(ModelBase, UserMixin):
    __tablename__ = 'registered_users'

    id = db.Column(db.Integer(), primary_key=True, autoincrement=True)

    provider = db.Column(db.String(16), nullable=False)
    subject = db.Column(db.String(), nullable=False)
    name = db.Column(db.String(), nullable=False)
    email = db.Column(db.String(), nullable=False, unique=True)
    profile_picture = db.Column(db.String(), nullable=False)

    registered_on = db.Column(db.DateTime(), nullable=False, server_default=functions.now())
    activated_on = db.Column(db.DateTime(), nullable=True)

    web_subscriptions = db.Column(db.String(), nullable=False, server_default='[]')

    roles: 'List[Role]' = db.relationship('Role', secondary=user_roles_table, back_populates='users')
    submissions = db.relationship('LearningDatapointSubmission', backref='registered_user', passive_deletes=True)

    __table_args__ = (
        db.UniqueConstraint('provider', 'subject'),
    )

    def __init__(self, provider: str, subject: str, name: str, email: str, profile_picture: str):
        if not isinstance(provider, str):
            raise expected('provider', provider, str)
        if not isinstance(subject, str):
            raise expected('subject', subject, str)
        if not isinstance(name, str):
            raise expected('name', name, str)
        if not isinstance(email, str):
            raise expected('email', email, str)
        if not isinstance(profile_picture, str):
            raise expected('profile_picture', profile_picture, str)

        self.provider = provider
        self.subject = subject
        self.name = name
        self.email = email
        self.profile_picture = profile_picture

    @staticmethod
    def create(provider: str, subject: str, name: str, email: str, profile_picture: str,
               add_to_db=True) -> 'RegisteredUser':
        user = RegisteredUser(provider, subject, name, email, profile_picture)

        if add_to_db:
            db.session.add(user)

        return user

    def delete(self):
        db.session.delete(self)

    # Overrides UserMixin.is_active
    @property
    def is_active(self):
        return self.activated_on is not None

    # Query methods
    @staticmethod
    def get_by_id(user_id: int) -> 'Optional[RegisteredUser]':
        return RegisteredUser.query.filter_by(id=user_id).first()

    @staticmethod
    def find_by_provider_id(provider: str, subject: str) -> 'Optional[RegisteredUser]':
        return RegisteredUser.query.filter_by(provider=provider, subject=subject).first()

    @staticmethod
    def find_by_email(email: str) -> 'Optional[RegisteredUser]':
        return RegisteredUser.query.filter_by(email=email).first()

    @staticmethod
    def get_all() -> 'List[RegisteredUser]':
        return RegisteredUser.query.all()

    @staticmethod
    def get_all_active() -> 'List[RegisteredUser]':
        return RegisteredUser.query.filter(RegisteredUser.activated_on != None).all()

    @staticmethod
    def get_all_by_role(role: 'Role') -> 'List[RegisteredUser]':
        return role.users
        # return RegisteredUser.query.filter(
        #     UserRoles.user_id == RegisteredUser.id,
        #     UserRoles.role_id == role.id
        # ).all()

    # Roles functions
    def get_roles(self) -> 'List[Role]':
        return self.roles

    def add_role(self, role: 'Role'):
        self.roles.append(role)

    def remove_role(self, role: 'Role'):
        self.roles.remove(role)

    def is_role(self, role: 'Union[str, Role]') -> bool:
        if isinstance(role, str):
            role = Role.find_by_name(role)
            return role is not None and role in self.roles
        elif isinstance(role, Role):
            return role in self.roles
        else:
            raise ValueError('role')

    # Subscriptions functions
    def get_subscriptions(self) -> 'List[AdminSubscription]':
        return json.loads(self.web_subscriptions)

    def set_subscriptions(self, subscriptions: 'List[AdminSubscription]'):
        self.web_subscriptions = json.dumps(subscriptions)

    def add_subscription(self, endpoint: str, keys: Dict[str, str]):
        subscriptions: 'List[AdminSubscription]' = []
        found = False

        for sub in self.get_subscriptions():
            subscriptions.append(sub)

            if sub['endpoint'] == endpoint:
                found = True

        if not found:
            subscriptions.append({'endpoint': endpoint, 'keys': keys})

        self.set_subscriptions(subscriptions)

    def remove_subscription(self, endpoint: str):
        self.set_subscriptions([sub for sub in self.get_subscriptions() if sub['endpoint'] != endpoint])

    @staticmethod
    def replace_subscription(old_endpoint: str, endpoint: str, keys: Dict[str, str]):
        for user in RegisteredUser.get_all():
            user.set_subscriptions([sub if sub['endpoint'] != old_endpoint else {'endpoint': endpoint, 'keys': keys}
                                    for sub in user.get_subscriptions()])

    def __hash__(self):
        return hash(self.id)
Ejemplo n.º 15
0
class FileModel(BasicModel):
    """
    文件模型
    """
    __tablename__ = 'FILE'

    md5_id = db.Column(db.String(length=64),
                       name='MD5_ID',
                       index=True,
                       nullable=False,
                       comment='文件MD5值')
    file_name = db.Column(db.String(length=64),
                          name='FILE_NAME',
                          nullable=False,
                          comment='文件名')
    file_format = db.Column(db.String(length=20),
                            name='FILE_FORMAT',
                            nullable=False,
                            comment='文件格式')
    file_size = db.Column(db.Numeric(precision=10, scale=2, asdecimal=False),
                          name='FILE_SIZE',
                          nullable=False,
                          default=0.00,
                          comment='文件大小')
    file_path_hash = db.Column(db.String,
                               name='FILE_PATH_HASH',
                               nullable=False,
                               comment='文件路径密文')

    @property
    def file_path(self):
        aes = AESUtil(current_app.config.get('DATA_PATH_KEY'))
        return aes.decrypt(self.file_path_hash)

    @file_path.setter
    def file_path(self, file_path):
        """
        设置路径
        :param file_path:
        :return:
        """
        # 文件路径加密
        aes = AESUtil(current_app.config.get('DATA_PATH_KEY'))
        self.file_path_hash = aes.encrypt(file_path)

    def __init__(self, file_base64=None, **kwargs):
        super(FileModel, self).__init__(**kwargs)
        self.file_base64 = file_base64

    def dao_down_file(self, id, md5_id):
        """
        文件查询
        :param id: 文件ID
        :param md5_id:
        :return:
        """
        return self.query.filter(FileModel.id == id,
                                 FileModel.md5_id == md5_id).first()

    def dao_init_file(self,
                      file_path,
                      id=None,
                      file_name=None,
                      subtransactions=False,
                      nested=False):
        """
        根据路径解析入库
        :param nested:
        :param subtransactions:
        :param file_name
        :param file_path: 文件路径
        :param id:
        :return:
        """
        with db.auto_commit_db(subtransactions=subtransactions,
                               nested=nested) as s:
            super().dao_create(id)
            # 计算文件 md5
            self.md5_id = FileUtil.get_md5_path(file_path)
            # noinspection PyAttributeOutsideInit
            self.file_path = file_path
            _, self.file_name, self.file_format = FileUtil.get_path_name_ext(
                file_path)

            if is_not_empty(file_name):
                self.file_name = file_name

            self.file_size = FileUtil.get_file_size(file_path)
            s.add(self)
Ejemplo n.º 16
0
class Camera(db.Model):
    __tablename__ = 'camera'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    ip = db.Column(db.String(200), nullable=False)
    name = db.Column(db.String(200))
    place_name = db.Column(db.String(200))
Ejemplo n.º 17
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
Ejemplo n.º 18
0
class Permission(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)
    roles = db.relationship('Role',
                            secondary=roles_permissions,
                            back_populates='permissions')
Ejemplo n.º 19
0
class Employee(db.Model):
    __tablename__ = 'employee_form'
    id = db.Column(db.Integer, primary_key=True)
    emp_name = db.Column(db.String(255))
    emp_email = db.Column(db.String(255))

    emp_code = db.Column(db.String(255))

    job_function = db.Column(db.String(255))

    date = db.Column(db.Date)

    reviewer_name = db.Column(db.String(255))
    reviewer_code = db.Column(db.String(255))

    self_assessment1 = db.Column(db.String(255))
    self_assessment1_comment1 = db.Column(db.String(255))

    self_assessment2 = db.Column(db.String(255))
    self_assessment2_comment2 = db.Column(db.String(255))

    self_assessment3 = db.Column(db.String(255))
    self_assessment3_comment3 = db.Column(db.String(255))

    self_assessment4 = db.Column(db.String(255))
    self_assessment4_comment4 = db.Column(db.String(255))

    self_assessment5 = db.Column(db.String(255))
    self_assessment5_comment5 = db.Column(db.String(255))

    self_assessment6 = db.Column(db.String(255))
    self_assessment6_comment6 = db.Column(db.String(255))

    rev_email = db.Column(db.String(255))

    IP_addr = db.Column(db.String(255))
    Location = db.Column(db.String(255))
    UserAgent = db.Column(db.String(255))
    OperatingSystem = db.Column(db.String(255))
    Time = db.Column(db.DateTime)
Ejemplo n.º 20
0
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, index=True)
    email = db.Column(db.String(254), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    name = db.Column(db.String(30))
    website = db.Column(db.String(255))
    bio = db.Column(db.String(120))
    location = db.Column(db.String(50))
    member_since = db.Column(db.DateTime, default=datetime.utcnow)
    avatar_s = db.Column(db.String(64))
    avatar_m = db.Column(db.String(64))
    avatar_l = db.Column(db.String(64))
    avatar_raw = db.Column(db.String(64))

    confirmed = db.Column(db.Boolean, default=False)
    locked = db.Column(db.Boolean, default=False)
    active = db.Column(db.Boolean, default=True)

    role_id = db.Column(db.Integer, db.ForeignKey('role.id'))

    role = db.relationship('Role', back_populates='users')

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        self.generate_avatar()
        self.set_role()

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def set_role(self):
        if self.role is None:
            if self.email == current_app.config['ALBUMY_ADMIN_EMAIL']:
                self.role = Role.query.filter_by(name='Administrator').first()
            else:
                self.role = Role.query.filter_by(name='User').first()
            db.session.commit()

    def validate_password(self, password):
        return check_password_hash(self.password_hash, password)

    def block(self):
        self.active = False
        db.session.commit()

    def unblock(self):
        self.active = True
        db.session.commit()

    def generate_avatar(self):
        avatar = Identicon()
        filenames = avatar.generate(text=self.username)
        self.avatar_s = filenames[0]
        self.avatar_m = filenames[1]
        self.avatar_l = filenames[2]
        db.session.commit()

    @property
    def is_admin(self):
        return self.role.name == 'Administrator'

    @property
    def is_active(self):
        return self.active

    def can(self, permission_name):
        permission = Permission.query.filter_by(name=permission_name).first()
        return permission is not None and self.role is not None and permission in self.role.permissions
Ejemplo n.º 21
0
class Family(BaseModel):
    __tablename__ = 'family'

    family_name = db.Column(db.String(128),
                            index=True,
                            nullable=True,
                            comment='家庭名字')
    member_name = db.Column(db.String(128), nullable=True, comment='成员名字')
    member_sex = db.Column(db.String(128), nullable=True, comment='成员性别')
    member_age = db.Column(db.String(128), nullable=True, comment='成员命令')
    member_city = db.Column(db.String(128), nullable=True, comment='成员所在城市')
    invitation_code = db.Column(db.String(128),
                                index=True,
                                nullable=True,
                                comment='家庭邀请码')
    child_id = db.Column(db.Integer, nullable=True, comment='孩子id')
    run_total = db.Column(db.Integer, default=0, comment='家庭总计跑步里程')
    task_stage = db.Column(db.Integer, default=0, comment='任务完成阶段')
    uid = db.Column(db.String(256), comment='用户uid')

    @classmethod
    def find_family_by_name(cls, name):
        exist = cls.query.filter(cls.family_name == name).first()
        return True if exist else False

    @classmethod
    def find_family_by_invitation_code(cls, code):
        family = cls.query.filter(cls.invitation_code == code).first()
        return family.id if family else None

    @classmethod
    def find_family_by_id(cls, _id, _uid):
        from api.models import User
        from api.models import Activity
        from api.models import Achievement
        # 先查询出这个家庭信息,在查询出加入这个家庭的其他用户信息
        family = cls.query.filter(cls.id == _id).first()
        if not family:
            return None
        other_members = User.find_by_family_id(family.id)

        uid_l = list()
        member_l = list()

        for member in other_members:
            uid = member.uid
            if isinstance(uid, str):
                if uid.isdigit():
                    uid = int(uid)
            elif isinstance(uid, int):
                uid = uid
            uid_l.append(uid)
            # 拿到成员id,查询名字
            nick, url = req_get_uid_info(uid)
            if str(family.uid) == str(uid):
                nick = family.member_name
            d = dict(nick=nick, head_url=url)
            member_l.append(d)

        # 孩子dict
        _d = dict(nick=family.get_child_name(),
                  head_url=Family.get_child_head())
        member_l.append(_d)

        # 查询这个家庭累计里程,同时排名, yp_run 表user_run_0-user_run_127 按用户uid%128
        # 1560405600 2019-06-13 14:00:00 开始时间取用户参加本活动的时间
        # 1561305600 2019-06-23 24:00:00
        activity = Activity.find_by_uid(_uid)
        if activity is None:
            start_time = 1560391200
        else:
            start_time = activity.created_at

        meter_total = 0
        testdb.ping()
        cursor = testdb.cursor()
        for uid in uid_l:
            table_name = 'user_run_{}'.format(uid % 128)
            sql = '''select sum(meter) / 1000 from {} where uid = {} and status in (1, 4) and start_time > {} and end_time < 1561305600 '''.format(
                table_name, uid, start_time)
            # print(sql)
            cursor.execute(sql)
            meter = cursor.fetchone()
            meter = int(meter[0]) if meter[0] else 0
            meter_total += meter
        cursor.close()

        # 比较一下这个家庭薪的总里程是否和之前相等
        if family.run_total != meter_total and meter_total > 0:
            family.update(run_total=meter_total)

        if family.run_total >= 1:
            # TODO 调用java接口给这个用户增加成就
            f = req_user_gain_achievement(_uid)
            if f:
                family.update(task_stage=1)
                # 接口调用成功
                Achievement.verify_add(uid=_uid)

        current_run_total = family.run_total if family.run_total else 0
        sql = 'select count(*) from family where run_total > {}'.format(
            current_run_total)
        rank = db.session.execute(sql).fetchone()
        rank = rank[0] if rank[0] else 1
        # 累计爱心值 系数13
        if rank > 120:
            rank = rank * 13
        sql = 'select sum(run_total) from family'
        love_total = db.session.execute(sql).fetchone()
        love_total = int(love_total[0]) if love_total[0] else 0
        # love_total 爱心值 这里要*一个系数,暂定为13
        love_total = int(love_total * 27.1) - 639000
        # print(love_total)

        d = dict(family_name=family.family_name,
                 member=member_l,
                 family_meter=meter_total,
                 rank=rank,
                 love_total=love_total,
                 invitation_code=family.invitation_code,
                 member_name=family.member_name,
                 child_name=family.get_child_name())
        # print(d)
        return d

    @classmethod
    def get_ranking_list_100(cls):
        results = cls.query.order_by(cls.run_total.desc()).limit(100)
        return results

    # @classmethod
    # def get_achievement(cls, family_id):
    #     from api.models import Achievement
    #     Achievement.get_achievement_by_uid()

    @classmethod
    def get_family_photo_100(cls):
        results = cls.query.order_by(cls.child_pic_num.desc()).limit(100)
        return results

    @classmethod
    def get_family_task_stage(cls, family_id):
        result = cls.query.filter(cls.id == family_id).first()
        return result if result else None

    @classmethod
    def find_family_by_id_to_wx(cls, _id):
        from api.models import User
        # 先查询出这个家庭信息,在查询出加入这个家庭的其他用户信息
        family = cls.query.filter(cls.id == _id).first()
        if not family:
            return None
        other_members = User.find_by_family_id(family.id)

        uid_l = list()
        member_l = list()

        for member in other_members:
            uid = member.uid
            uid_l.append(uid)
            # 拿到成员id,查询名字
            nick, url = req_get_uid_info(uid)
            if str(family.uid) == str(uid):
                nick = family.member_name
            d = dict(nick=nick, head_url=url)
            member_l.append(d)

        _d = dict(nick=family.get_child_name(),
                  head_url=Family.get_child_head())
        member_l.append(_d)

        d = dict(family_name=family.family_name,
                 member=member_l,
                 invitation_code=family.invitation_code,
                 child_name=family.get_child_name())
        # print(d)
        return d

    def get_child_name(self):
        from api.models import Child
        return Child.find_by_id(self.child_id).child_name

    @classmethod
    def get_child_head(cls):
        return 'https://linked-runner.b0.upaiyun.com/avatar/avatar_default.png!/sq/200'
Ejemplo n.º 22
0
class Announcement(db.Model):
    __tablename__ = 'announcement'
    id = db.Column(db.Integer, primary_key=True)
    time = db.Column(db.DateTime, nullable=False)
    title = db.Column(db.String(256), nullable=False)
    body = db.Column(db.Text, nullable=False)
Ejemplo n.º 23
0
class Like(BaseModel):
    __tablename__ = 'like'

    uid = db.Column(db.String(256), index=True, comment='用户uid')
    child_photo_id = db.Column(db.Integer, index=True, comment='孩子照片id')
Ejemplo n.º 24
0
class User(db.Model, UserMixin):
    query_class = UserQuery

    # user roles
    ADMIN = 100
    RESELLER = 200
    EDITOR = 300
    MEMBER = 400
    # FUGUANG = 200
    # FGA = 300

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.Unicode(60), unique=True, nullable=False)
    email = db.Column(db.String(150), unique=False, nullable=False)
    date_joined = db.Column(db.DateTime, default=datetime.utcnow)
    role = db.Column(db.Integer, default=MEMBER)

    active = db.Column(db.Boolean, default=True)
    _password = db.Column("password", db.String(80))
    _openid = db.Column("openid", db.String(80), unique=True)
    is_active = db.Column(db.Boolean, default=True)

    def __init__(self, *args, **kwargs):
        super(User, self).__init__(*args, **kwargs)

    def __str__(self):
        return self.username

    def __repr__(self):
        return "<%s>" % self

    def is_active(self):
        return self.active

    def _get_password(self):
        return self._password

    def _set_password(self, password):
        self._password = sha1(password).hexdigest()

    password = db.synonym("_password",
                          descriptor=property(_get_password, _set_password))

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

    def _get_openid(self):
        return self._openid

    def _set_openid(self, openid):
        self._openid = generate_password_hash(openid)

    openid = db.synonym("_openid",
                        descriptor=property(_get_openid, _set_openid))

    @property
    def is_admin(self):
        return self.role >= self.ADMIN

    # @property
    # def is_fuguang(self):
    #     return self.role >= self.FUGUANG

    # @property
    # def is_fga(self):
    #     return self.role >= self.FGA

    # @property
    # def system(self):
    #     if self.role == self.FUGUANG:
    #         return 'FUGUANG'
    #     elif self.role == self.FGA:
    #         return 'FGA'
    #     return ''

    def check_openid(self, openid):
        if self.openid is None:
            return False
        return check_password_hash(self.openid, openid)

    @cached_property
    def gravatar(self):
        if not self.email:
            return ''
        md5 = hashlib.md5()
        md5.update(self.email.strip().lower())
        return md5.hexdigest()

    def gravatar_url(self, size=80):
        if not self.gravatar:
            return ''

        return "http://www.gravatar.com/avatar/%s.jpg?s=%d" % (self.gravatar,
                                                               size)
Ejemplo n.º 25
0
class Subject(db.Model):
    __tablename__ = 'subject'
    id = db.Column(db.Integer, primary_key=True)
    subject_name = db.Column(db.String(30), unique=True, nullable=False)
Ejemplo n.º 26
0
class Tag(db.Model):
    __tablename__ = 'tags'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
Ejemplo n.º 27
0
class VideoConnInfo(db.Model):
    __tablename__ = 'VIDEO_CONN_INFO'
    id = db.Column(db.String(36), default=gen_uuid, primary_key=True)
    ccbins_id = db.Column(db.String(9))
    eqmt_id = db.Column(db.String(20))
    index_code = db.Column(db.String(120))
    cct_rcrd_inf = db.Column(db.String(300))
    status = db.Column(db.String(2))
    param1 = db.Column(db.String(120))
    param2 = db.Column(db.String(120))
    param3 = db.Column(db.String(120))
    param4 = db.Column(db.String(120))
    param5 = db.Column(db.String(120))
    param6 = db.Column(db.String(120))
    param7 = db.Column(db.String(120))
    param8 = db.Column(db.String(120))
    param9 = db.Column(db.String(120))
    param10 = db.Column(db.String(120))
    last_udt_dt_tm = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
Ejemplo n.º 28
0
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50))
    email = db.Column(db.String(50))
Ejemplo n.º 29
0
class Lecturer(db.Model):
    __tablename__ = 'lecturer'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    last_name = db.Column(db.String(30), nullable=False)
    surname = db.Column(db.String(30), nullable=False)
Ejemplo n.º 30
0
class AD(db.Model):
    '''广告'''

    __bind_key__ = 'analytics'
    __tablename__ = 'ad'

    id = Column(db.Integer(unsigned=True), primary_key=True)
    code = Column(db.String(50), nullable=False, unique=True, index=True)
    name = Column(db.String(50), nullable=False)

    product_id = Column(db.Integer(unsigned=True), index=True, nullable=False)
    product_name = Column(db.String(50), nullable=False, index=True)

    medium_id = Column(db.Integer(unsigned=True), nullable=False)
    medium_name = Column(db.String(50), nullable=False)

    place_id = Column(db.Integer(unsigned=True), nullable=False, index=True)
    place_name = Column(db.String(50), nullable=False)

    ad_id = Column(db.Integer(unsigned=True), nullable=False, index=True)
    ad_name = Column(db.String(50), nullable=False)
    ad_mode = Column(db.SmallInteger(unsigned=True),
                     nullable=False,
                     index=True)  #方式(1:文字、2:图片)
    ad_type = Column(db.SmallInteger(unsigned=True),
                     nullable=False,
                     index=True)  #类型(1:专题、2:链接)
    ad_img = Column(db.String(200))  #图片
    ad_txt = Column(db.String(100))  #文字
    ad_url = Column(db.String(200))  #广告地址
    to_url = Column(db.String(200), nullable=False)  #目标地址

    remark = Column(db.String(500))  #备注

    status = Column(db.SmallInteger(unsigned=True), nullable=False,
                    default=1)  #当前状态(1:启用)
    created = Column(db.DateTime, default=datetime.now)

    @classmethod
    def generate_code(cls, product_id, medium_id, place_id, ad_id):
        return md5('%s$%s$%s$%s' %
                   (product_id, medium_id, place_id, ad_id)).hexdigest()

    @property
    def mode_name(self):
        return AD_CONTENT_MODES[self.ad_mode]

    @property
    def type_name(self):
        return AD_CONTENT_TYPES[self.ad_type]

    @property
    def link_url(self):
        if self.ad_type == 1:
            scheme, netloc, path, query_string, fragment = urlsplit(
                self.to_url)
            query_params = parse_qs(query_string)
            query_params['code'] = [self.code]
            new_query_string = urlencode(query_params, doseq=True)
            return urlunsplit(
                (scheme, netloc, path, new_query_string, fragment))
        elif self.ad_type == 2:
            return urlunsplit(
                ('http', AD_UNION_URL, '',
                 urlencode({
                     'code': self.code,
                     'to': quote(self.to_url)
                 },
                           doseq=True), ''))