Exemplo n.º 1
0
class UserData(db.Model, CRUDMixin, TimeMixin):
    """
    collection of user data, from query used as cache, data encrpted with aes
    """
    id = db.Column(db.UUID(as_uuid=True), default=uuid.uuid4, primary_key=True)
    data = db.Column(db.String())
    name = db.Column(db.String())
    user_id = db.Column(db.String, db.ForeignKey('user.id'))
    status = db.Column(db.String())
    # client_id = StringField(default='client_')

    def to_json(self):
        return {
            'data': self.data,
            'name': self.name,
            'created': self.created,
            'status': self.status
        }

    def get_client(self):
        client = redis_store.get(user_data.client_id, None)
        return client

    def lock_save(self, pw):
        in_len = len(self.data)
        pad_size = 16 - (in_len % 16)
        self.data = self.data.ljust(in_len + pad_size, chr(pad_size))
        if len(pw) < 16:
            pw += '0' * (16 - len(pw))
        iv = binascii.a2b_hex('000102030405060708090a0b0c0d0e0f')
        obj = AES.new(pw, AES.MODE_CBC, iv)
        self.data = str(binascii.b2a_base64(obj.encrypt(self.data)))[2:-2]
        self.save()
Exemplo n.º 2
0
class User(UserMixin, db.Model, TimestampMixin):
    """
    User model.
    `account_type`: `basic` and `premium`, also `admin`, but not sure about that yet. It"s `basic` by default
    `status`: by default inactive, becomes active after email confirmation
    """
    __tablename__ = "users"

    id = db.Column(UUID(as_uuid=True), primary_key=True, nullable=False, default=uuid4)
    email = db.Column(db.String(255), nullable=False)
    first_name = db.Column(db.String(255), nullable=False)
    last_name = db.Column(db.String(255), nullable=False)
    password = db.Column(PasswordType(schemes=["bcrypt"]), nullable=False)
    is_active = db.Column(db.Boolean(), nullable=False, server_default="1")
    confirmed = db.Column(db.Boolean(), nullable=False, server_default="0")
    email_confirmed_at = db.Column(db.DateTime())

    roles = db.relationship("Role", secondary="user_roles")

    __table_args__ = (
        UniqueConstraint("email", name="uq_users_email"),
    )

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

    @staticmethod
    def auth(email, password):
        user = User.query.filter_by(email=email).first()
        if user and user.password == password:
            return user
        return None

    def __repr__(self):
        return f"User(id={self.id}, email={self.email}, account_type={self.account_type}, status={self.status})"
Exemplo n.º 3
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
        }
Exemplo n.º 4
0
class Event(db.Model):
    __tablename__ = 'events'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), nullable=False)
    description = db.Column(db.String(80), nullable=False)
    date = db.Column(db.Date, nullable=False)
    time = db.Column(db.Time, nullable=False)
    type = db.Column(ChoiceType(EventType), nullable=False)
    category = db.Column(ChoiceType(CategoryType), nullable=False)
    location_id = db.Column(db.Integer, db.ForeignKey("locations.id"))
    location = db.relationship("Location",
                               back_populates="events",
                               lazy='joined')
    address = db.Column(db.String(80), nullable=False)
    seats = db.Column(db.Integer)

    enrollments = db.relationship("Enrollment",
                                  back_populates="event",
                                  lazy='joined')

    participants = db.relationship('Participant',
                                   secondary='enrollments',
                                   back_populates='events',
                                   lazy='joined')

    def __str__(self):
        return f'{self.title}'
Exemplo n.º 5
0
class Address(db.Model):
    '''
    地址管理
    '''
    __tablename__ = 'addresses'
    id = db.Column(db.Integer, primary_key=True)
    state = db.Column(db.String(100))
    city = db.Column(db.String(100))
    street = db.Column(db.String(255))
    telephone1 = db.Column(db.String(100))
    telephone2 = db.Column(db.String(100))
    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())

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

    @property
    def fields(self):
        return ['state', 'city', 'street', 'telephone1', 'telephone2']

    def to_json(self):
        result = {f: getattr(self, f) for f in self.fields}
        result.update({'id': str(self.id)})
        return result
Exemplo n.º 6
0
class CompulsoryPurchaseOrderInvestigation(db.Model, OrderedMixin):

    compulsory_purchase_order_investigation = db.Column(db.Integer(),
                                                        primary_key=True,
                                                        nullable=False)
    status = db.Column(db.String())
    inspector_report_url = db.Column(db.String())
    decision_url = db.Column(db.String())
    start_date = db.Column(db.Date())
    end_date = db.Column(db.Date())

    compulsory_purchase_order_id = db.Column(
        db.String,
        db.ForeignKey('compulsory_purchase_order.compulsory_purchase_order'))
    compulsory_purchase_order = db.relationship(
        'CompulsoryPurchaseOrder', back_populates='investigations')

    def is_final_state(self):
        return self.status in final_states

    def __hash__(self):
        return hash(self.compulsory_purchase_order_investigation)

    def __eq__(self, other):
        return self.compulsory_purchase_order_investigation == other.compulsory_purchase_order_investigation
Exemplo n.º 7
0
class StoreActivity(db.Model):
    '''
    系统用户
    '''
    __tablename__ = 'store_activities'
    id = db.Column(db.Integer, primary_key=True)
    type_id = db.Column(db.Integer)
    name = db.Column(db.String(100))
    poster_img = db.Column(db.String(255))
    desc = db.Column(db.Text)
    every_count = db.Column(db.Integer)
    max_count = db.Column(db.Integer)
    store_id = db.Column(db.String(255))
    is_hot = db.Column(db.Boolean, default=True)
    create_time = db.Column(db.DateTime, default=db.func.current_timestamp())
    is_deleted = db.Column(db.Boolean, default=False)
    deleted_time = db.Column(db.DateTime)

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

    def mark_deleted(self):
        if self.is_deleted:
            return
        self.is_deleted = True
        self.deleted_date = datetime.datetime.utcnow()
        db.session.commit()
Exemplo n.º 8
0
class Feature(db.Model):
    feature = db.Column(db.String(256), primary_key=True)
    item = db.Column(db.String(256))
    data = db.Column(JSONB)
    geometry = db.Column(Geometry(srid=4326))
    name = db.Column(db.Text)
    publication = db.Column(db.String(64))
Exemplo n.º 9
0
class Licence(db.Model):
    licence = db.Column(db.String(256), primary_key=True)
    name = db.Column(db.String(256))
    url = db.Column(db.Text)
    text = db.Column(db.Text)

    publications = db.relationship('Publication', backref='licence', lazy=True)
Exemplo n.º 10
0
class Component(db.Model):
    __tablename__ = 'components'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    deploy_version = db.Column(db.String(16))
    private = db.Column(db.Boolean, default=True)
    mean = db.Column(db.Float(precision=1), default=0)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    def generate_token(self):
        s = Serializer(current_app.config['SECRET_KEY'])
        return s.dumps({'id': self.id})

    @classmethod
    def verify_token(cls, token):
        """
        :raises BadSignature
        :param token:
        :return: component object that match token
        """
        s = Serializer(current_app.config['SECRET_KEY'])
        data = s.loads(token)
        component = cls.query.get(data['id'])
        return component

    def component_files(self):
        return [
            filename for filename in os.listdir(
                current_app.config['COMPONENT_UPLOAD_FOLDER'])
            if filename.startswith(str(self.id))
        ]

    def to_json(self):
        return {
            "pid": self.id,
            "name": self.name,
            "deploy_version": self.deploy_version,
            "private": self.private
        }

    @classmethod
    def generate_fake(cls, user):
        from shutil import copyfile
        from random import randint
        fake = Component(name='Fake Component',
                         deploy_version=randint(0, 10),
                         owner_id=user.id)
        db.session.add(fake)
        db.session.commit()
        """apply deploy version again"""
        copyfile(
            current_app.config['FAKE_UPLOAD'],
            os.path.join(current_app.config['UPLOAD_FOLDER'], 'components',
                         '%s.%s' % (str(fake.id), 'jar')))
        return fake

    def __repr__(self):
        return '<Component %r>' % self.name
Exemplo n.º 11
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)
Exemplo n.º 12
0
class Location(db.Model):
    __tablename__ = 'locations'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), unique=True, nullable=False)
    code = db.Column(db.String(8), unique=True, nullable=False)
    events = db.relationship("Event", back_populates="location", lazy='joined')

    def __str__(self):
        return f'{self.title}'
Exemplo n.º 13
0
class Category(db.Model):
    __tablename__ = 'categories'
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(15), unique=True, nullable=False)
    title = db.Column(db.String(80), unique=True, nullable=False)
    meals = db.relationship("Meal", back_populates="category", lazy='joined')

    def __str__(self):
        return f'{self.title}'
Exemplo n.º 14
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    hashed_password = db.Column(db.String(512), unique=True, nullable=False)

    def __repr__(self):
        return self.username

    def hash_password(self, password):
        return generate_password_hash(password)
Exemplo n.º 15
0
class Corpus(db.Model):
    """Data model for a corpus."""

    __tablename__ = 'corpus'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False)
    status = db.Column(db.String(32), index=False, nullable=False)

    def __repr__(self):
        return '<Corpus {}>'.format(self.name)
Exemplo n.º 16
0
class Book(db.Model):
    __tablename__ = 'book'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    title = db.Column(db.String(64), nullable=True)
    author = db.Column(db.String(256), nullable=True)
    page_number = db.Column(db.Integer, nullable=True)
    book_url = db.Column(db.String(256), nullable=False)
    thumbnaiUrl = db.Column(db.String(256), nullable=True)
Exemplo n.º 17
0
class Video(db.Model):
    __tablename__ = 'video'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    title = db.Column(db.String(64), nullable=True)
    text = db.Column(db.String(512), nullable=True)
    video_url = db.Column(db.String(256), nullable=False)
    thumbnaiUrl = db.Column(db.String(256), nullable=True)
Exemplo n.º 18
0
class Device(db.Model):

    __tablename__ = 'device'

    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, unique=True, nullable=True)
    versionName = db.Column(db.String(256), unique=True, nullable=True)
    applicationName = db.Column(db.String(256), unique=False, nullable=True)
    deviceName = db.Column(db.String(256), unique=False, nullable=True)
    systemName = db.Column(db.String(256), unique=False, nullable=True)
class DynamicModel(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    uuid = db.Column(db.Integer, default=random_integer, unique=True, nullable=False)
    # uuid = db.Column(UUID(as_uuid=True), unique=True, nullable=False)
    schema = db.Column(db.String(100), nullable=False)
    status = db.Column(db.String(15), nullable=False, default='draft')
    json_blob = db.Column(db.JSON, nullable=False)

    def __repr__(self):
        return f"DynamicModel('{self.id}', '{self.uuid}', '{self.schema}', '{self.status}', '{self.json_blob}')"
Exemplo n.º 20
0
class Sound(db.Model):

	__tablename__ = 'sound'

	id = db.Column(db.Integer, primary_key=True)
	user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
	category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
	time = db.Column(db.TIME, nullable=True)
	singer = db.Column(db.String(64), nullable=True)
	sound_url = db.Column(db.String(256), nullable=False)
	name = db.Column(db.String(128), nullable=True)
Exemplo n.º 21
0
class Card(db.Model):
    '''
    系统用户
    '''
    __tablename__ = 'cards'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    desc = db.Column(db.String(500))
    price = db.Column(db.Integer, default=199)

    def __unicode__(self):
        return '%s' % str(self.id)
Exemplo n.º 22
0
class User(db.Model):
    '''
    系统用户
    '''
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    weixin_openid = db.Column(db.String(100))
    mobile = db.Column(db.String(100))
    password = db.Column(db.String(255))
    nickname = db.Column(db.String(255))
    gender = db.Column(db.INT, default=0)
    create_time = db.Column(db.DateTime, default=db.func.current_timestamp())
    is_deleted = db.Column(db.Boolean, default=False)
    deleted_time = db.Column(db.DateTime)

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

    def generate_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)

    @classmethod
    def create(cls, weixin_openid, nickname):
        user = User(weixin_openid=weixin_openid)
        db.session.add(user)
        db.session.commit()
        return user

    @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

    def mark_deleted(self):
        if self.is_deleted:
            return
        self.is_deleted = True
        self.deleted_date = datetime.datetime.utcnow()
        db.session.commit()
Exemplo n.º 23
0
class User(db.Model):
    """定义数据模型"""
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.usernames
Exemplo n.º 24
0
class Applicant(db.Model):
    __tablename__ = 'applicants'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    phone = db.Column(db.String(20), nullable=False)
    email = db.Column(db.String(80), nullable=False)
    status = db.Column(ChoiceType(ApplicantStatus), nullable=False)
    group_id = db.Column(db.Integer, db.ForeignKey("groups.id"))
    group = db.relationship("Group",
                            back_populates="applicants",
                            lazy='joined')

    def __str__(self):
        return f'{self.name}'
Exemplo n.º 25
0
class PlanningAuthority(db.Model):

    id = db.Column(db.String(64), primary_key=True)
    ons_code = db.Column(db.String(9))
    name = db.Column(db.String(256))
    website = db.Column(db.String())
    local_plans = db.relationship(
        'LocalPlan',
        secondary=planning_authority_plan,
        lazy='dynamic',
        back_populates='planning_authorities',
    )

    def sorted_plans(self, reverse=False, deleted=False):
        plans = self.local_plans.filter(LocalPlan.deleted == deleted).all()
        return sorted(plans, reverse=reverse)

    def get_earliest_plan_start_year(self):
        try:
            first = next(p for p in self.sorted_plans()
                         if p.plan_start_year is not None)
            if first is not None:
                return first.plan_start_year.year
            else:
                return None
        except StopIteration:
            return None

    def get_latest_plan_end_year(self):
        try:
            first = next(p for p in self.sorted_plans(reverse=True)
                         if p.plan_end_year is not None)
            if first is not None:
                return first.plan_end_year.year
            else:
                return None
        except StopIteration:
            return None

    def code(self):
        return self.id.split(':')[-1]

    def to_dict(self):
        data = {
            'id': self.id,
            'name': self.name,
            'ons_code': self.ons_code,
            'plans': [plan.to_dict(self.id) for plan in self.local_plans]
        }
        return data
Exemplo n.º 26
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))
Exemplo n.º 27
0
class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    email = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(128), nullable=False)

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

    def check_password(self, password):
        return check_password_hash(self.password, password)

    def __str__(self):
        return f'{self.name}'
Exemplo n.º 28
0
class Todo(db.Model):
    """data model"""
    __tablename__ = 'todo'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255), nullable=False)
    posted_on = db.Column(db.Date, default=datetime.utcnow)
    status = db.Column(db.Boolean(), default=False)

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

    def __repr__(self):
        return "<Todo '%s'>" % self.title

    def store_to_db(self):
        """save to database"""

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

    def delete_todo(self):
        """delete data"""

        db.session.delete(self)
        db.session.commit()
Exemplo n.º 29
0
class Target(db.Model, SoftDeleteMixin):
    __tablename__ = 'target'

    id = db.Column(
        UUID(as_uuid=True),
        default=uuid4,
        primary_key=True,
    )
    last_message_id = db.Column(
        UUID(as_uuid=True),
        nullable=True,
    )
    type = db.Column(
        db.String(25),
        nullable=False,
    )

    messages = db.relationship('Message', )

    __mapper_args__ = {
        'polymorphic_identity': __tablename__,
        'polymorphic_on': type,
    }

    def to_dict(self):
        return dict(
            id=self.id,
            last_message_id=self.last_message_id,
            members=[m.member_id for m in self.target_members],
            is_deleted=True if self.removed_at is not None else False,
            removed_at=self.removed_at,
            created_at=self.created_at,
        )
Exemplo n.º 30
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'))