示例#1
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True)

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

    def __repr__(self):
        return '<User %r>' % self.email
示例#2
0
class User(db.Model):
    email = db.Column(db.String(255), primary_key=True)
    username = db.Column(db.String(255))
    upassword = db.Column(db.String(255))
    uauthority = db.Column(db.Integer)

    def __init__(self, username, password, email, authority):
        self.email = email
        self.username = username
        self.upassword = password
        self.uauthority = authority
示例#3
0
class UserConnection(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    user = db.relationship(User)
    backend = db.Column(db.String)
    external_id = db.Column(db.String)
    data = db.Column(db.Text)

    def __repr__(self):
        return "<UserConnection %r:%r:%r>" % (self.user_id, self.backend,
                                              self.external_id)
示例#4
0
class User(db.Model):
    __tablename__ = "users"

    id = db.Column(UUID(as_uuid=True), default=uuid.uuid4, unique=True, primary_key=True)
    email = db.Column(db.String(128), unique=True, nullable=False)
    name = db.Column(db.String(128), nullable=False)
    surname = db.Column(db.String(128), nullable=False)
    role = db.Column(db.String(128), nullable=False)
    phone = db.Column(db.String(128))
    city = db.Column(db.String(128))
    type = db.Column(db.String(50), nullable=False)
    blocked = db.Column(db.Boolean(), default=False, nullable=False)

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

    def __init__(self, **kwargs):
        self.assert_key(kwargs, 'name')
        self.assert_key(kwargs, 'surname')
        self.assert_key(kwargs, 'email')

        if kwargs.get('role', '') not in ROLES:
            raise ValueError('Invalid user role')

        if not re.match(re.compile(r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"), kwargs['email']):
            raise ValueError('Invalid email')

        self.email = kwargs['email']
        self.name = kwargs['name']
        self.surname = kwargs['surname']
        self.role = kwargs['role']
        self.phone = kwargs.get('phone', None)
        self.city = kwargs.get('city', None)

    def assert_key(self, values_dict, key):
        if not values_dict.get(key, ''):
            raise ValueError('Missing user %s' % key)

    def serialize(self):
        return {
            "id": str(self.id),
            "email": self.email,
            "name": self.name,
            "surname": self.surname,
            "role": self.role,
            "phone": self.phone,
            "city": self.city,
            "blocked": self.blocked
        }

    def password_matches(self, password):
        raise NotImplementedError()

    def update(self, values):
        for key,value in values.items():
            setattr(self, key, value)
示例#5
0
class Personnel(db.Model):
    perid = db.Column(db.String(255), primary_key=True)
    pername = db.Column(db.String(255))
    perdegree = db.Column(db.String(255))
    pereb = db.Column(db.String(255))
    pertitle = db.Column(db.String(255))

    def __init__(self, perid, pername, perdegree, pereb, pertitle):
        self.perid = perid
        self.pername = pername
        self.perdegree = perdegree
        self.pereb = pereb
        self.pertitle = pertitle
示例#6
0
class Monograph(db.Model):
    moissn = db.Column(db.String(255), primary_key=True)
    moname = db.Column(db.String(255))
    moauthor = db.Column(db.String(255))
    mopress = db.Column(db.String(255))
    modp = db.Column(db.String(255))

    def __init__(self, moissn, moname, moauthor, mopress, modp):
        self.moissn = moissn
        self.moname = moname
        self.moauthor = moauthor
        self.mopress = mopress
        self.modp = modp
示例#7
0
文件: list.py 项目: flisz/prop
class List(Model):
    """
    Base Model Provides:
        pk (primary key)
        created_at (creation date)
    """
    name = db.Column(db.String(), nullable=False)
    items = db.relationship('Item', backref='items', lazy=True)

    def __repr__(self):
        return f'<List {self.id} name: {self.name}>'

    @property
    def dictionary(self):
        return {
            'pk':
            self.pk,
            'created_at':
            self.created_at,
            'name':
            self.name,
            'items': [
                item.dictionary
                for item in Item.query.filter(Item.list_id == self.pk)
            ]
        }
示例#8
0
class Server(db.Model):
    __tablename__ = "servers"

    id = db.Column(UUID(as_uuid=True),
                   default=uuid.uuid4,
                   unique=True,
                   primary_key=True)
    nombre = db.Column(db.String(256), nullable=False)
    token = db.Column(db.String(256), nullable=False)

    def __init__(self, **kwargs):
        self.assert_key(kwargs, 'nombre')
        self.assert_key(kwargs, 'token')

        self.nombre = kwargs['nombre']
        self.token = kwargs['token']

    def assert_key(self, values_dict, key):
        if not values_dict.get(key, ''):
            raise ValueError('Missing server %s' % key)

    def serialize(self):
        return {"id": str(self.id), "nombre": self.nombre, "token": self.token}
示例#9
0
class Item(Model):
    """
    Base Model Provides:
        pk (primary key)
        created_at (creation date)
    """
    summary = db.Column(db.String(), nullable=False)
    details = db.Column(db.String(), nullable=False)
    active = db.Column(db.Boolean, nullable=False, default=False)
    list_pk = db.Column(db.Integer, db.ForeignKey('list.pk'), nullable=False)

    def __repr__(self):
        return f'<Item {self.pk} details: {self.details} summary: {self.summary} active: {self.active} list_pk: {self.list_pk}>'

    @property
    def dictionary(self):
        return {
            'pk': self.pk,
            'created_at': self.created_at,
            'summary': self.summary,
            'details': self.details,
            'active': self.active,
            'list_pk': self.list_pk
        }
示例#10
0
class Paper(db.Model):
    paperid = db.Column(db.String(255), primary_key=True)
    papername = db.Column(db.String(255))
    paperfa = db.Column(db.String(255))
    paperca = db.Column(db.String(255))
    paperpt = db.Column(db.String(255))
    paperpn = db.Column(db.String(255))
    papervp = db.Column(db.String(255))
    papersp = db.Column(db.String(255))
    paperep = db.Column(db.String(255))
    paperct = db.Column(db.String(255))

    def __init__(self, paperid, papername, paperfa, paperca, paperpt, paperpn,
                 papervp, papersp, paperep, paperct):
        self.paperid = paperid
        self.papername = papername
        self.paperfa = paperfa
        self.paperca = paperca
        self.paperpt = paperpt
        self.paperpn = paperpn
        self.papervp = papervp
        self.papersp = papersp
        self.paperep = paperep
        self.paperct = paperct
示例#11
0
class Patent(db.Model):
    paid = db.Column(db.String(255), primary_key=True)
    paname = db.Column(db.String(255))
    paapplicant = db.Column(db.String(255))
    pada = db.Column(db.String(255))
    patype = db.Column(db.String(255))
    paie = db.Column(db.String(255))
    paapc = db.Column(db.String(255))
    paauc = db.Column(db.String(255))

    def __init__(self, paid, paname, paapplicant, pada, patype, paie, paapc,
                 paauc):
        self.paid = paid
        self.paname = paname
        self.paapplicant = paapplicant
        self.pada = pada
        self.patype = patype
        self.paie = paie
        self.paapc = paapc
        self.paauc = paauc
示例#12
0
class SRTA(db.Model):
    staid = db.Column(db.String(255), primary_key=True)
    staname = db.Column(db.String(255))
    statype = db.Column(db.String(255))
    stawinner = db.Column(db.String(255))
    start = db.Column(db.String(255))
    statime = db.Column(db.String(255))
    stait = db.Column(db.String(255))
    stanote = db.Column(db.String(255))

    def __init__(self, staid, staname, statype, stawinner, start,
                 statime, stait, stanote):
        self.staid = staid
        self.staname = staname
        self.statype = statype
        self.stawinner = stawinner
        self.start = start
        self.statime = statime
        self.stait = stait
        self.stanote = stanote
示例#13
0
class Meeting(db.Model):
    mid = db.Column(db.String(255), primary_key=True)
    mname = db.Column(db.String(255))
    mmember = db.Column(db.String(255))
    mtime = db.Column(db.String(255))
    maddress = db.Column(db.String(255))
    mtype = db.Column(db.String(255))
    mnote = db.Column(db.String(255))

    def __init__(self, mid, mname, mmember, mtime, maddress, mtype, mnote):
        self.mid = mid
        self.mname = mname
        self.mmember = mmember
        self.mtime = mtime
        self.maddress = maddress
        self.mtype = mtype
        self.mnote = mnote
示例#14
0
class BookBnBUser(User):
    password = db.Column(db.String(128))

    __mapper_args__ = {
        'polymorphic_identity': 'bookbnb_user'
    }

    def __init__(self, **kwargs):
        self.assert_key(kwargs, 'password')

        if len(kwargs['password']) < 8:
            raise ValueError('Invalid user password: expected length of 8 characters')

        super().__init__(**kwargs)

        self.change_password(kwargs['password'])

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

    def change_password(self, new_password):
        hashed_password = generate_password_hash(new_password, method='sha256')
        self.password = hashed_password
示例#15
0
class Model(db.Model, QueryMixin):
    """Abstract base class for all app models.

    Provides an `id` & `created_at` column to every model.

    To define models, follow this example:

        from .base import Model

        class MyModel(Model):
            # model definition
    """
    __abstract__ = True

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

    @declared_attr
    def created_at(cls):
        return db.Column(ArrowType, default=utcnow, nullable=False, index=True)

    @property
    def class_name(self):
        """Shortcut for returning class name."""
        return unicode(self.__class__.__name__)

    @classmethod
    def __ignore__(cls):
        """Custom class attr that lets us control which models get ignored.

        We are using this because knowing whether or not we're actually dealing
        with an abstract base class is only possible late in the class's init
        lifecycle.

        This is used by the dynamic model loader to know if it should ignore.
        """
        return cls.__name__ in ('Model',)  # can add more abstract base classes here

    def __repr__(self):
        """"Returns a string representation of every object.

        Useful for logging & error reporting.
        Example:

            >>> obj = MyModel()
            >>> print obj
            MyModel.123

        Can be overridden by subclasses to customize string representation.
        """
        return u"{}.{}".format(self.class_name, self.id)

    @declared_attr
    def __tablename__(cls):
        """Generate a __tablename__ attr for every model that does not have
        inherited tables.

        Ensures table names match the model name without needing to declare it.
        """
        if has_inherited_table(cls):
            return None
        return cls.__name__.lower()

    ##################################################################################
    # I added the base methods below to augment the foundation built up by bob waycott
    ##################################################################################

    @property
    def dictionary(self):
        return {}

    @property
    def __skip_attrs__(self):
        return []

    def update(self, data):
        caught_id = data.get('id')
        if caught_id and self.id != caught_id:
            _id = self.id
            db.session.close()
            raise ApiDatabaseError(403,
                                   f"Cannot modify primary keys got:({caught_id}) for: {_id}")
        invalid_keys = list()
        for key, value in data.items():
            if any([key == skip for skip in self.__skip_attrs__]) or not hasattr(self, key):
                invalid_keys.append(value)
        if len(invalid_keys) > 0:
            db.session.close()
            raise ApiDatabaseError(422, f"Invalid Database Fields: {','.join(invalid_keys)}")
        else:
            for key, value in data.items():
                try:
                    setattr(self, key, value)
                except Exception as e:
                    log.exception(e)
                    db.session.close()
                    raise ApiDatabaseError(400, f"Rejected for : {key}")
            try:
                returns = self.dictionary
                self.save()
                db.session.close()
                return returns
            except StatementError as e:
                db.session.close()
                raise ApiDatabaseError(400, f'Rejected for: {e.orig}')
        raise ApiDatabaseError(400, f'Rejected!')

    @staticmethod
    def toTimeString(time_stamp):
        timezone = 'US/Mountain'
        return str(time_stamp.to(timezone))
示例#16
0
class Model(db.Model, QueryMixin):
    """Abstract base class for all app models.

    Provides a `pk` & `created_at` column to every model.

    To define models, follow this example:

        from .base import Model

        class MyModel(Model):
            # model definition
    """
    __abstract__ = True

    pk = db.Column(db.Integer, primary_key=True)

    @declared_attr
    def created_at(cls):
        return db.Column(ArrowType, default=utcnow, nullable=False, index=True)

    @property
    def class_name(self):
        """Shortcut for returning class name."""
        return unicode(self.__class__.__name__)

    @classmethod
    def __ignore__(cls):
        """Custom class attr that lets us control which models get ignored.

        We are using this because knowing whether or not we're actually dealing
        with an abstract base class is only possible late in the class's init
        lifecycle.

        This is used by the dynamic model loader to know if it should ignore.
        """
        return cls.__name__ in ('Model',
                                )  # can add more abstract base classes here

    def __repr__(self):
        """"Returns a string representation of every object.

        Useful for logging & error reporting.
        Example:

            >>> obj = MyModel()
            >>> print obj
            MyModel.123

        Can be overridden by subclasses to customize string representation.
        """
        return u"{}.{}".format(self.class_name, self.pk)

    @declared_attr
    def __tablename__(cls):
        """Generate a __tablename__ attr for every model that does not have
        inherited tables.

        Ensures table names match the model name without needing to declare it.
        """
        if has_inherited_table(cls):
            return None
        return cls.__name__.lower()
示例#17
0
class Project(db.Model):
    proid = db.Column(db.String(255), primary_key=True)
    proname = db.Column(db.String(255))
    proyear = db.Column(db.String(255))
    procategory = db.Column(db.String(255))
    proheader = db.Column(db.String(255))
    promember = db.Column(db.String(255))
    prost = db.Column(db.String(255))
    proet = db.Column(db.String(255))
    prouu = db.Column(db.String(255))
    propf = db.Column(db.String(255))
    progu = db.Column(db.String(255))

    def __init__(self, proid, proname, proyear, procategory, proheader,
                 promember, prost, proet, prouu, propf, progu):
        self.proid = proid
        self.proname = proname
        self.proyear = proyear
        self.procategory = procategory
        self.proheader = proheader
        self.promember = promember
        self.prost = prost
        self.proet = proet
        self.prouu = prouu
        self.propf = propf
        self.progu = progu
示例#18
0
 def created_at(cls):
     return db.Column(ArrowType, default=utcnow, nullable=False, index=True)
示例#19
0
class UserProfile(UserMixin, Model):
    """
    .base.Model provides:
        id (primary key)
        created_at (creation date)
    flask_login.UserMixin provides:
    """

    alternate_id = db.Column(db.String(256), nullable=False, unique=True)
    social_id = db.Column(db.String(256), nullable=True, unique=True)
    nickname = db.Column(db.String(256), nullable=True)
    email = db.Column(db.String(256), nullable=True)
    picture = db.Column(db.String(256), nullable=True)
    name = db.Column(db.String(256), nullable=True)
    family_name = db.Column(db.String(256), nullable=True)
    given_name = db.Column(db.String(256), nullable=True)
    locale = db.Column(db.String(16), default='en', nullable=False)
    updated_at = db.Column(ArrowType, default=utcnow, index=True)
    email_verified = db.Column(db.Boolean, nullable=True, default=False)

    def __repr__(self):
        return f'<User {self.id}: email: {self.email} nickname: {self.nickname}>'

    @property
    def __skip_attrs__(self):
        return [
            "__repr__", 'records', 'manager', 'patron', 'provider',
            'scheduler', 'addresses', 'created_at', 'update'
        ]

    @property
    def dictionary(self):
        return {
            'id': self.id,
            'created_at': self.toTimeString(self.created_at),
            'alternate_id': self.alternate_id,
            'social_id': self.social_id,
            'email': self.email,
            'email_verified': self.email_verified,
            'name': self.name,
            'family_name': self.family_name,
            'given_name': self.given_name,
            'locale': self.locale,
            'updated_at': self.toTimeString(self.updated_at),
        }

    @property
    def all_records(self):
        return []

    @property
    def all_records_serialized(self):
        return []

    @classmethod
    def get_or_create(cls, sub):
        existing_user = cls.query.filter(cls.alternate_id == sub).one_or_none()
        if existing_user:
            return existing_user
        else:
            new_user = cls(alternate_id=sub)
            new_user.save()
            this_id = new_user.id
            db.session.close()
            initialized_user = cls.get(this_id)
            return initialized_user