Ejemplo n.º 1
0
class Market(Base):
    __tablename__ = 'market'
    code = db.Column(db.String, primary_key=True)
    name = db.Column(db.String)
    api_code = db.Column(db.String)
    timezone = db.Column(TimezoneType(backend='pytz'))
    open = db.Column(db.Time(timezone=True))
    close = db.Column(db.Time(timezone=True))
    base_url = db.Column(db.String)

    # Foreign key relationships
    stocks = relationship('Stock',
                          order_by='Stock.ticker',
                          back_populates='market')

    def __init__(self, code, **kwargs):
        self.code = code
        self.name = kwargs.pop('name', None)
        self.api_code = kwargs.pop('api_code', None)
        self.timezone = kwargs.pop('timezone', None)
        self.open = kwargs.pop('open', None)
        self.close = kwargs.pop('close', None)
        self.base_url = kwargs.pop('base_url', None)

    def get_all_stocks(self):
        pass
Ejemplo n.º 2
0
def downgrade():
    op.alter_column(
        'project',
        'timezone',
        existing_type=TimezoneType(backend='pytz'),
        type_=sa.Unicode(40),
    )
Ejemplo n.º 3
0
class Person(db.Model, BaseMixin, SerializerMixin):

    first_name = db.Column(db.String(80), nullable=False)
    last_name = db.Column(db.String(80), nullable=False)
    email = db.Column(EmailType, unique=True)
    phone = db.Column(db.String(30))
    active = db.Column(db.Boolean(), default=True)
    last_presence = db.Column(db.Date())
    password = db.Column(db.Binary(60))
    shotgun_id = db.Column(db.Integer, unique=True)
    timezone = db.Column(TimezoneType(backend="pytz"),
                         default=pytz_timezone("Europe/Paris"))
    locale = db.Column(LocaleType, default=Locale("en", "US"))

    data = db.Column(JSONB)

    skills = db.relationship("Department", secondary=department_link)

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

    def full_name(self):
        if sys.version_info[0] < 3:
            return "%s %s" % (self.first_name.encode("utf-8"),
                              self.last_name.encode("utf-8"))
        else:
            return "%s %s" % (self.first_name, self.last_name)
Ejemplo n.º 4
0
class Person(db.Model, BaseMixin, SerializerMixin):
    """
    Describe a member of the studio (and an API user).
    """
    first_name = db.Column(db.String(80), nullable=False)
    last_name = db.Column(db.String(80), nullable=False)
    email = db.Column(EmailType, unique=True)
    phone = db.Column(db.String(30))

    active = db.Column(db.Boolean(), default=True)
    last_presence = db.Column(db.Date())

    password = db.Column(db.Binary(60))
    desktop_login = db.Column(db.String(80))
    shotgun_id = db.Column(db.Integer, unique=True)
    timezone = db.Column(
        TimezoneType(backend="pytz"),
        default=pytz_timezone("Europe/Paris")
    )
    locale = db.Column(LocaleType, default=Locale("en", "US"))
    data = db.Column(JSONB)
    role = db.Column(db.String(30), default="user")
    has_avatar = db.Column(db.Boolean(), default=False)

    skills = db.relationship(
        "Department",
        secondary=department_link
    )

    def __repr__(self):
        if sys.version_info[0] < 3:
            return "<Person %s>" % self.full_name().encode("utf-8")
        else:
            return "<Person %s>" % self.full_name()

    def full_name(self):
        return "%s %s" % (
            self.first_name,
            self.last_name
        )

    def serialize(self, obj_type="Person"):
        data = SerializerMixin.serialize(self, "Person")
        data["full_name"] = self.full_name()
        return data

    def serialize_safe(self):
        data = SerializerMixin.serialize(self, "Person")
        data["full_name"] = self.full_name()
        del data["password"]
        return data
Ejemplo n.º 5
0
class Users(Base):
    __tablename__ = 'users'
    __table_args__ = {'extend_existing': True}

    TYPE_GENDER = (
        ('m', u'Мужской'),
        ('f', u'Женский'),
        ('n', u'Не установлен'),
    )

    TYPE_STATUS = ()

    TYPE_TYPE = ()

    id           = Column(Integer, primary_key=True)
    firstname    = Column(String(128), nullable=False)
    lastname     = Column(String(128), nullable=False)
    gender       = Column(ChoiceType(TYPE_GENDER))
    phone        = Column(PhoneNumberType())
    city_id      = Column(Integer, ForeignKey('cities.id'), nullable=False)
    address      = Column(Text)
    time_zone    = Column(TimezoneType(backend='pytz'))
    bio          = Column(Text)
    created      = Column(DateTime, nullable=False)
    last_visit   = Column(DateTime)
    email        = Column(String(256))
    password     = Column(PasswordType(schemes=['md5_crypt']))
    # uStatus      = Column(ChoiceType(TYPE_STATUS))
    birthdate    = Column(Date)
    # uType        = Column(ChoiceType(TYPE_TYPE))
    userpic_type = Column(String(1))
    userpic_id   = Column(Integer)

    rels         = relationship('UsersRels', backref='users')
    chats        = relationship('UsersChat', backref='users')
    values       = relationship('UsersValues', backref='users')
    msgr_log     = relationship('MsgrLog', backref='users')
    msgr_threads = relationship('UsersMsgrThreads', backref='users')

    def __init__(self):
        pass

    def __repr__(self):
        return '<User([{}] {} {})>'.format(self.id, self.firstname, self.lastname)
Ejemplo n.º 6
0
class User(db.Model):
    id = db.Column(UUIDType(binary=False), default=uuid.uuid4, primary_key=True)

    # use a regular string field, for which we can specify a list of available choices later on
    type = db.Column(db.String(100))

    # fixed choices can be handled in a number of different ways:
    enum_choice_field = db.Column(db.Enum(EnumChoices), nullable=True)
    sqla_utils_choice_field = db.Column(ChoiceType(AVAILABLE_USER_TYPES), nullable=True)
    sqla_utils_enum_choice_field = db.Column(ChoiceType(EnumChoices, impl=db.Integer()), nullable=True)

    first_name = db.Column(db.String(100))
    last_name = db.Column(db.String(100))

    # some sqlalchemy_utils data types (see https://sqlalchemy-utils.readthedocs.io/)
    email = db.Column(EmailType, unique=True, nullable=False)
    website = db.Column(URLType)
    ip_address = db.Column(IPAddressType)
    currency = db.Column(CurrencyType, nullable=True, default=None)
    timezone = db.Column(TimezoneType(backend='pytz'))

    dialling_code = db.Column(db.Integer())
    local_phone_number = db.Column(db.String(10))

    featured_post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
    featured_post = db.relationship('Post', foreign_keys=[featured_post_id])

    @hybrid_property
    def phone_number(self):
        if self.dialling_code and self.local_phone_number:
            number = str(self.local_phone_number)
            return "+{} ({}) {} {} {}".format(self.dialling_code, number[0], number[1:3], number[3:6], number[6::])
        return

    @phone_number.expression
    def phone_number(cls):
        return sql.operators.ColumnOperators.concat(cast(cls.dialling_code, db.String), cls.local_phone_number)

    def __str__(self):
        return "{}, {}".format(self.last_name, self.first_name)

    def __repr__(self):
        return "{}: {}".format(self.id, self.__str__())
Ejemplo n.º 7
0
class User(Base):
    __tablename__ = 'user'

    id = Column(BigInteger, Sequence('user_id_seq') )
    email = Column(EmailType, nullable=False)
    first_name = Column(String(25), nullable=True)
    last_name = Column(String(35), nullable=True)
    fullname = Column(String(75), nullable=True)
    twitter = Column(String(35), nullable=True)
    country = Column(CountryType, nullable=True)
    _phone = Column(Unicode(20), nullable=True)
    timezone = Column(TimezoneType(backend='pytz'))
    password = Column(PasswordType(
        schemes=[
            'pbkdf2_sha512',
            'md5_crypt'
        ],

        deprecated=['md5_crypt']
    ))
    create_date = Column(DateTime(), default=datetime.now, nullable=False)
    update_date = Column(DateTime(), default=datetime.now, nullable=False, onupdate=datetime.now)

    phone = orm.composite(
        PhoneNumber,
        _phone,
        country, 
        nullable=True
    )

    __table_args__ = (
        PrimaryKeyConstraint('id', name='user_pk'),
        UniqueConstraint('email', name='user_email_unique')
    )

    def __repr__(self):
        return "<User(email='%s', fullname='%s' )>" % (
            self.email,
            self.fullname
        )
Ejemplo n.º 8
0
class Cities(Base):
    __tablename__ = 'cities'
    __table_args__ = {'extend_existing': True}

    id = Column(Integer, primary_key=True)
    country_id = Column(Integer, ForeignKey('countries.id'), nullable=False)
    name = Column(String(256), nullable=False)
    name_orig = Column(String(256), nullable=False)
    time_zone = Column(TimezoneType(backend='pytz'), nullable=False)
    description = Column(Text)

    users = relationship("Users", backref='cities')

    def __init__(self, country, name, name_orig, time_zone, description=None):
        self.country_id = country
        self.name = name
        self.name_orig = name_orig
        self.time_zone = time_zone
        self.description = description

    def __repr__(self):
        return "<Cities([{}] {})>".format(self.id, self.name)
Ejemplo n.º 9
0
def client_info_table():
    t = {
        'name':
        CLIENT_INFO_TABLE_NAME,
        'desc':
        'The client info.',
        'columns': [
            pk(),
            Column('hostname',
                   String(128),
                   default=get_hostname(),
                   unique=True,
                   sqlite_on_conflict_unique='REPLACE',
                   comment='The client hostname.'),
            Column('tz',
                   TimezoneType(backend='pytz'),
                   default=tzlocal.get_localzone_name(),
                   comment='The client time zone.'),
            created_at(),
            updated_at(),
        ]
    }
    return t
Ejemplo n.º 10
0
class Person(db.Model, BaseMixin, SerializerMixin):
    """
    Describe a member of the studio (and an API user).
    """

    first_name = db.Column(db.String(80), nullable=False)
    last_name = db.Column(db.String(80), nullable=False)
    email = db.Column(EmailType, unique=True)
    phone = db.Column(db.String(30))

    active = db.Column(db.Boolean(), default=True)
    last_presence = db.Column(db.Date())

    password = db.Column(db.LargeBinary(60))
    desktop_login = db.Column(db.String(80))
    shotgun_id = db.Column(db.Integer, unique=True)
    timezone = db.Column(
        TimezoneType(backend="pytz"),
        default=pytz_timezone(config.DEFAULT_TIMEZONE),
    )
    locale = db.Column(LocaleType, default=Locale("en", "US"))
    data = db.Column(JSONB)
    role = db.Column(db.String(30), default="user")
    has_avatar = db.Column(db.Boolean(), default=False)

    notifications_enabled = db.Column(db.Boolean(), default=False)
    notifications_slack_enabled = db.Column(db.Boolean(), default=False)
    notifications_slack_userid = db.Column(db.String(60), default="")
    notifications_mattermost_enabled = db.Column(db.Boolean(), default=False)
    notifications_mattermost_userid = db.Column(db.String(60), default="")
    notifications_discord_enabled = db.Column(db.Boolean(), default=False)
    notifications_discord_userid = db.Column(db.String(60), default="")

    departments = db.relationship("Department",
                                  secondary=department_link,
                                  lazy="joined")

    def __repr__(self):
        if sys.version_info[0] < 3:
            return "<Person %s>" % self.full_name().encode("utf-8")
        else:
            return "<Person %s>" % self.full_name()

    def full_name(self):
        return "%s %s" % (self.first_name, self.last_name)

    def serialize(self, obj_type="Person", relations=False):
        data = SerializerMixin.serialize(self, "Person", relations=relations)
        data["full_name"] = self.full_name()
        return data

    def serialize_safe(self, relations=False):
        data = SerializerMixin.serialize(self, "Person", relations=relations)
        data["full_name"] = self.full_name()
        del data["password"]
        return data

    def present_minimal(self, relations=False):
        data = SerializerMixin.serialize(self, "Person", relations=relations)
        return {
            "id": data["id"],
            "first_name": data["first_name"],
            "last_name": data["last_name"],
            "full_name": self.full_name(),
            "has_avatar": data["has_avatar"],
            "active": data["active"],
            "departments": data.get("departments", []),
            "role": data["role"],
        }

    def set_departments(self, department_ids):
        from zou.app.models.department import Department

        self.departments = []
        for department_id in department_ids:
            department = Department.get(department_id)
            if department is not None:
                self.departments.append(department)
        self.save()

    @classmethod
    def create_from_import(cls, person):
        del person["type"]
        del person["full_name"]
        is_update = False
        previous_person = cls.get(person["id"])

        if "password" in person:
            person["password"] = person["password"].encode()

        department_ids = None
        if "departments" in person:
            department_ids = person.pop("departments", None)

        if previous_person is None:
            previous_person = cls.create(**person)
        else:
            is_update = True
            previous_person.update(person)

        if department_ids is not None:
            previous_person.set_departments(department_ids)

        return (previous_person, is_update)
Ejemplo n.º 11
0
class Address:
    """Base address information.

    This mixin provides the base interface for an Address.
    Design decision was to require at least the following fields:

        * locality: City/Town of this address
        * country: ISO 3166 representation of a Country.

    Additionally we have a field called info that stores a dict with more detailed information.
    """

    country = sa.Column(sautils.CountryType, index=True, nullable=False)
    """Country of this address.

    Country will be stored as a ISO 3166-2 information.
    i.e.: DE, BR, ID
    """

    locality = sa.Column(sa.String(255), index=True, nullable=False)
    """Locality of this address.

    Locality could be a City, a Town or similar.
    i.e.: Bangkok, Berlin, São Paulo
    """

    formatted_address = sa.Column(sa.String(255), nullable=True)
    """Address to be displayed on the user interface.

    We use this as a fail safe against problems in the geocoding.
    i.e.: Schlesische Straße 27, Kreuzberg, Berlin, 10997, DE
    """

    info = sa.Column(JSONB, info={'colanderalchemy': {'typ': schema.JSONType}})
    """Structure containing address information.

    Info expected schema::

        {
          'additional_info': 'House 3, Entry C, 1st. floor, c/o GLG',
          'formatted_address': 'Schlesische Straße 27, Kreuzberg, Berlin, 10997, DE',
          'place_id': 'ChIJ8-exwVNOqEcR8hBPr-VUmdQ',
          'province': 'Berlin',
          'locality': 'Berlin',
          'sublocality': 'Kreuzberg',
          'route': 'Schlesische Straße',
          'street_number': '27',
          'country': 'DE',
          'postal_code': '10997'
        }

    Ref: https://maps-apis.googleblog.com/2016/11/address-geocoding-in-google-maps-apis.html
    """

    timezone = sa.Column(TimezoneType(backend='pytz'), default='UTC')
    """Timezone in which this address is located.

    i.e.: UTC, Europe/Berlin
    """

    _coordinates = sa.Column('coordinates',
                             POINT,
                             index=True,
                             info={
                                 'colanderalchemy': {
                                     'title': 'Geo JSON Point coordinates',
                                     'typ': schema.Coordinate,
                                     'missing': colander.drop,
                                 }
                             })
    """Attribute to store the coordinates (lat, lng) for this object.

    Should always be accessed using :func:`Address.coordinates` property.
    """
    @hybrid_property
    def coordinates(self) -> dict:
        """Return coordinates as a GeoJSON object.

         For a Point it is like::

            'coordinates': {
                'type': 'Point',
                'coordinates': [52.4994805, 13.4491646]
            },

        :returns: Coordinates as a GeoJSON object
        """
        coordinates = self._coordinates
        if not isinstance(coordinates, str):
            session = object_session(self)
            if session:
                if coordinates is not None:
                    coordinates = session.scalar(coordinates.ST_AsGeoJSON())
                else:
                    return
        return json.loads(coordinates)

    @coordinates.setter
    def coordinates(self, value: dict):
        """Set coordinates from a GeoJSON.

        :param value: Dictionary containing a GeoJSON object
        """
        if isinstance(value, (list, tuple)):
            # We assume is (lat, lng)
            # so, to deal with GeoJSON, we swap it
            value = {'type': 'Point', 'coordinates': [value[1], value[0]]}

        # this should keep only for the model tests
        elif isinstance(value, dict):
            if isinstance(value['coordinates'][0], str):
                return

        value = json.dumps(value)
        self._coordinates = value

    @coordinates.expression
    def coordinates(cls):
        """Expression to be used on gis queries."""
        return cls._coordinates

    @hybrid_method
    def distance(self, value=(0.0, 0.0)):
        """Distance between this address and another location."""
        if self.coordinates:
            return sa.func.ST_Distance(self.coordinates,
                                       sa.func.ST_MakePoint(*value), True)

    @hybrid_property
    def latlng(self):
        """Return coordinates as a tuple.

        :returns: A tuple containing latitude and longitude
        :rtype: tuple
        """
        coordinates = self.coordinates
        point = coordinates.get('coordinates', None) if coordinates else None
        if point:
            lng, lat = point
            return lat, lng
Ejemplo n.º 12
0
class Person(db.Model, BaseMixin, SerializerMixin):
    """
    Describe a member of the studio (and an API user).
    """

    first_name = db.Column(db.String(80), nullable=False)
    last_name = db.Column(db.String(80), nullable=False)
    email = db.Column(EmailType, unique=True)
    phone = db.Column(db.String(30))

    active = db.Column(db.Boolean(), default=True)
    last_presence = db.Column(db.Date())

    password = db.Column(db.LargeBinary(60))
    desktop_login = db.Column(db.String(80))
    shotgun_id = db.Column(db.Integer, unique=True)
    timezone = db.Column(TimezoneType(backend="pytz"),
                         default=pytz_timezone("Europe/Paris"))
    locale = db.Column(LocaleType, default=Locale("en", "US"))
    data = db.Column(JSONB)
    role = db.Column(db.String(30), default="user")
    has_avatar = db.Column(db.Boolean(), default=False)

    notifications_enabled = db.Column(db.Boolean(), default=False)
    notifications_slack_enabled = db.Column(db.Boolean(), default=False)
    notifications_slack_userid = db.Column(db.String(60), default="")

    skills = db.relationship("Department", secondary=department_link)

    def __repr__(self):
        if sys.version_info[0] < 3:
            return "<Person %s>" % self.full_name().encode("utf-8")
        else:
            return "<Person %s>" % self.full_name()

    def full_name(self):
        return "%s %s" % (self.first_name, self.last_name)

    def serialize(self, obj_type="Person", relations=False):
        data = SerializerMixin.serialize(self, "Person", relations=relations)
        data["full_name"] = self.full_name()
        return data

    def serialize_safe(self, relations=False):
        data = SerializerMixin.serialize(self, "Person", relations=relations)
        data["full_name"] = self.full_name()
        del data["password"]
        return data

    def present_minimal(self, relations=False):
        data = SerializerMixin.serialize(self, "Person", relations=relations)
        return {
            "id": data["id"],
            "first_name": data["first_name"],
            "last_name": data["last_name"],
            "full_name": self.full_name(),
            "has_avatar": data["has_avatar"],
            "active": data["active"],
            "desktop_login": data["desktop_login"]
        }

    @classmethod
    def create_from_import(cls, person):
        del person["type"]
        del person["full_name"]
        previous_person = cls.get(person["id"])
        if "password" in person:
            person["password"] = person["password"].encode()
        if previous_person is None:
            return (cls.create(**person), False)
        else:
            previous_person.update(person)
            return (previous_person, True)
Ejemplo n.º 13
0
class Users(MultiTenantBase, UserMixin, db.Model):
    name = Column(String(127), nullable=True)  # optional
    active = Column(Boolean, nullable=False, default=True)  # req security
    admin = Column(Boolean, nullable=False, default=False)
    email = Column(String(64), index=True, unique=True, nullable=False)
    password = Column(String(72), nullable=False)  # bcrypt.length = 60
    timezone = Column(TimezoneType(backend='pytz'))

    confirmed_at = Column(DateTime)
    last_login_at = Column(DateTime)
    current_login_at = Column(DateTime)
    login_count = Column(Integer, default=0)
    last_login_ip = Column(IPAddressType)
    current_login_ip = Column(IPAddressType)

    roles = db.relationship('Roles',
                            secondary=roles_users,
                            backref='users',
                            lazy='dynamic')

    def __init__(self,
                 name='',
                 email='',
                 desc='',
                 password=None,
                 active=True,
                 admin=False,
                 org=None,
                 roles=None,
                 timezone=None):
        self.active = active
        self.admin = admin
        self.desc = desc
        self.email = email
        self.name = name
        self.timezone = timezone

        if password:
            self.set_password(password)
        if roles is not None:
            if type(roles) is not list:
                roles = [roles]
            self.roles = roles

        if type(org) is str:
            orgobj = Orgs.query.filter_by(name=org).first()
            if orgobj:
                org = orgobj
            else:
                org = Orgs(name=org)
                db.session.add(org)
                db.session.commit()
        self.org = org

    def set_password(self, password):
        try:
            self.password = encrypt_password(password)
        except RuntimeError:  # :-/
            with app.app_context():
                self.password = encrypt_password(password)

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

    def __repr__(self):
        return '<%s %r>' % (self.__class__.__name__, self.email)