Exemplo n.º 1
0
class User(db.Model, UserMixin):
    username = CharField(unique=True, index=True)
    password = CharField()
    email = CharField()
    first_name = CharField()
    last_name = CharField()
    #confirmed_at = DateTimeField(null=True)
    active = BooleanField(default=True)
    workplace = ForeignKeyField(Company, related_name='works_for')
    roles = ManyToManyField(Role,
                            related_name='users',
                            through_model=UserRolesProxy)
    approves_for = ManyToManyField(Company,
                                   related_name='approved_by',
                                   through_model=ApproverCompaniesProxy)
    full_name = property(lambda self: "%s %s" %
                         (self.first_name, self.last_name))

    def gravatar_url(self, size=80):
        return "http://www.gravatar.com/avatar/%s?d=identicon&s=%d" % \
            (md5(self.email.strip().lower().encode('utf-8')).hexdigest(), size)

    class Meta:
        order_by = ('username', )
        table_alias = 'u'

    def __str__(self):
        return self.full_name
Exemplo n.º 2
0
class PlaceAmenities(Model):
    place = ManyToManyField(Place)
    amenity = ManyToManyField(Amenity)

    class Meta:
        database = database
        order_by = ("id", )  # what is the extra space for?
Exemplo n.º 3
0
class Groupe(BaseModel):
    nom = peewee.CharField(unique=True)
    date_creation = peewee.DateTimeField(
        verbose_name=u"Date de création du groupe",
        default=datetime.datetime.now)
    participants = ManyToManyField(Eleve, related_name="fait_partie")
    cours = ManyToManyField(Cours, related_name="groupes_attaches")

    affichage = [('nom', 200), ('cours', 200), ('participants', 400)]
    requis = ['nom', 'participants', 'cours']

    def __str__(self):
        return self.nom
Exemplo n.º 4
0
class Lecture(BaseModel):
    lecture_id = PrimaryKeyField()
    disp_lecture = TextField()
    must = JSONField(null=True)
    week = IntegerField()
    jigen = IntegerField()

    teachers = ManyToManyField(Teacher, related_name="lectures")
    rooms = ManyToManyField(Room, related_name="lectures")
    classes = ManyToManyField(Class, related_name="lectures")

    def __repr__(self):
        return '<Lecture_Model id={0}, disp={1}, must={2}, week={3}, jigen={4}, teacherscount={5}, roomscount={6}, classescount={7}>'.format(
            self.lecture_id, self.disp_lecture, self.must, self.week,
            self.jigen, len(self.teachers), len(self.rooms), len(self.classes))
Exemplo n.º 5
0
class Tweets(BaseModel):
    tweet_id = IntegerField(primary_key=True)
    tweets = CharField(unique=True, max_length=150)
    creation_date = DateTimeField()
    user = CharField()
    is_processed = BooleanField()
    trackers = ManyToManyField(TrackWord, related_name='tweets')
Exemplo n.º 6
0
class Conversation(BaseModel):
    id = CharField(primary_key=True)
    members = ManyToManyField(User, related_name='conversations')
    group = BooleanField()

    @property
    def logger(self):
        message_logger = logging.getLogger(self.id)
        message_formatter = logging.Formatter(
            '[%(message_time)s] <%(username)s> %(message)s')
        file_handler = logging.handlers.RotatingFileHandler(os.path.join(
            settings.LOGGING_DIRECTORY, '{}.log'.format(self.id)),
                                                            maxBytes=20000000,
                                                            backupCount=5)
        file_handler.setFormatter(message_formatter)
        message_logger.setLevel(logging.INFO)
        if len(message_logger.handlers) > 0:
            for handler in message_logger.handlers:
                if not isinstance(handler,
                                  logging.handlers.RotatingFileHandler):
                    message_logger.addHandler(file_handler)
        else:
            message_logger.addHandler(file_handler)
        return message_logger

    def __str__(self):
        return self.id
Exemplo n.º 7
0
class Extract_Model(Model):
    filetype = CharField()
    version = CharField()
    architecture = CharField()
    compiler = CharField()
    sections = ManyToManyField(Section_Model, related_name='sections')

    created = DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = db

    @classmethod
    def add_entry(cls, **kwargs):
        entry = None

        try:
            entry = cls.create(
                filetype=kwargs['filetype'],
                version=kwargs['version'],
                architecture=kwargs['architecture'],
                compiler=kwargs['compiler'],
            )
            for item in kwargs['sections']:
                entry.sections.add(Section_Model.add_entry(item))
        except Exception as e:
            print 'Something went wrong with the database'
            print e

        return entry
Exemplo n.º 8
0
class Event(Model):
    """ Training event model """
    eventname = CharField()
    eventdatetime = DateTimeField()
    competitors = ManyToManyField(User, related_name="events")
    eventcontent = CharField()
    ## 0: orienteering, 1: running
    eventtype = IntegerField()
    ##0:monday, 1:tuesday 2: wednesday, ,4: thursday 5: saturday, 6: sunday
    eventday = CharField()

    class Meta:
        database = db_proxy
        order_by = ("-eventdatetime", )

    @classmethod
    def create_event(cls, eventname, eventdatetime, eventtype, eventday,
                     eventcontent):
        """creates a new event"""
        try:
            cls.create(eventname=eventname,
                       eventdatetime=eventdatetime,
                       eventtype=eventtype,
                       eventday=eventday,
                       eventcontent=eventcontent)
        except IntegrityError:
            raise ValueError("Event already exists")
Exemplo n.º 9
0
class Item(ConnectionModel):
    name = pw.CharField()
    description = pw.TextField()
    allowed_users = ManyToManyField(User, related_name='allowed_items')
    pub_date = pw.DateTimeField(default=datetime.datetime.now)
    tags = pw.CharField(null=True)
    category = pw.ForeignKeyField(Category)
Exemplo n.º 10
0
class Course(peewee.Model):
    name = peewee.CharField(max_length=10)

    students = ManyToManyField(Student, related_name='courses')

    class Meta:
        database = database
Exemplo n.º 11
0
class Project(BaseModel):
    name = CharField(db_column='NAME', null=False)
    created_date = DateTimeField(default=datetime.datetime.now())
    description = TextField(db_column="description", null=True)
    persons = ManyToManyField(Person, related_name="projects")

    class Meta:
        db_table = 'project'
Exemplo n.º 12
0
class Group(ConnectionModel):

    """
    Basic model to group users.
    """
    name = orm.CharField(max_length=255, unique=True)
    users = ManyToManyField(User, related_name='usergroups')
    pub_date = orm.DateTimeField(default=datetime.datetime.now)
Exemplo n.º 13
0
class Course(peewee.Model):
    name = peewee.CharField(max_length=10)

    params = {M2M_RELATED: 'courses'}
    students = ManyToManyField(Student, **params)

    class Meta:
        database = database
Exemplo n.º 14
0
class Post(database.Model):
    """Stores list of domains where posts have been delivered to."""
    nodes = ManyToManyField(Node, related_name="posts")
    guid = CharField()
    protocol = CharField()
    created_at = DateTimeField(default=datetime.datetime.now)

    class Meta:
        indexes = ((("guid", "protocol"), True), )
Exemplo n.º 15
0
class Talk(peewee.Model):
    id = peewee.IntegerField()
    title = peewee.CharField()
    meetup = peewee.ForeignKeyField(Meetup, related_name='talks')
    speakers = ManyToManyField(Speaker, through_model=DeferredTalkSpeaker)

    class Meta:
        database = database
        db_table = 'meetups_talk'
Exemplo n.º 16
0
class Tweet(BaseModel):

    """
    Tweet model.
    Stores the tweet's unique ID as a primary key along with the user, text and date.
    """
    id = peewee.BigIntegerField(unique=True, primary_key=True)
    user = peewee.ForeignKeyField(User, related_name='tweets', index=True)
    text = peewee.TextField()
    date = peewee.DateTimeField(index=True)
    tags = ManyToManyField(Hashtag)
    urls = ManyToManyField(URL)
    language = peewee.ForeignKeyField(Language, null=True)
    mentions = ManyToManyField(User)
    reply_to_user = peewee.ForeignKeyField(
        User, null=True, index=True, related_name='replies')
    reply_to_tweet = peewee.BigIntegerField(null=True, index=True)
    retweet = peewee.ForeignKeyField(
        'self', null=True, index=True, related_name='retweets')
Exemplo n.º 17
0
class MovieModel(Model):
    subject_id = CharField(unique=True, max_length=400)
    title = CharField(max_length=800)
    genres = ManyToManyField(GenreModel, related_name='genres')
    countries = ManyToManyField(CountryModel, related_name='countries')
    actors = ManyToManyField(ActorModel, related_name='actors')
    writers = ManyToManyField(WriterModel, related_name='writers')
    directors = ManyToManyField(DirectorModel, related_name='directors')

    rating = FloatField(null=True)
    url = CharField()
    description = CharField(null=True, max_length=10000)
    release_time = DateTimeField(null=True)
    year = IntegerField(null=True)
    month = IntegerField(null=True)
    day = IntegerField(null=True)

    class Meta:
        global db
        database = db  # This model uses the "people.db" database.
Exemplo n.º 18
0
Arquivo: model.py Projeto: giskar/shop
class Order(db.Model):

    goods = ManyToManyField(Goods, related_name='orders')
    #goods = CharField()
    name = CharField(max_length=55)
    phone = IntegerField()
    pay_method = CharField(max_length=55)
    del_method = CharField(max_length=55)
    pub_date = DateTimeField(default=datetime.datetime.now)

    def __str__(self):
        return '%s' % (self.name)
Exemplo n.º 19
0
class Video(Model):
    title = TextField()
    duration = IntegerField()
    url = TextField()
    thumbnail_url = TextField()

    site = ForeignKeyField(Site)
    tags = ManyToManyField(Tag, related_name="videos")

    class Meta:
        database = db
        db_table = 'videos'
Exemplo n.º 20
0
class Meetup(peewee.Model):
    number = peewee.IntegerField()
    date = peewee.DateTimeField()
    is_ready = peewee.BooleanField()
    sponsors = ManyToManyField(Sponsor, through_model=DeferredMeetupSponsor)

    class Meta:
        database = database
        db_table = 'meetups_meetup'

    def title(self):
        return 'PyWaw #{}'.format(self.number)
Exemplo n.º 21
0
class Forrest_Model(Model):
    created = DateTimeField(default=datetime.datetime.now)
    sha256sum = CharField(max_length="64")
    raw = ManyToManyField(Raw_Model, related_name='raw')
    extract = ManyToManyField(Extract_Model, related_name='extract')

    class Meta:
        database = db

    @classmethod
    def add_entry(cls, forrest):
        entry = None

        try:
            entry = cls.create(sha256sum=forrest.raw.get_sha256())
            entry.raw.add(forrest.raw.add_entry())
            entry.extract.add(forrest.extract.add_entry())
        except Exception as e:
            print 'Something went wrong with the database'
            print e

        return entry
Exemplo n.º 22
0
class Task(BaseModel):
    name = CharField(db_column='NAME', null=False)
    created_date = DateTimeField(default=datetime.datetime.now())
    begin_date = DateTimeField(null=True)
    end_date = DateTimeField(null=True)
    shot = ForeignKeyField(db_column='shot_id',
                           rel_model=Shot,
                           to_field='id',
                           related_name="tasks")
    persons = ManyToManyField(Person, related_name="tasks")
    status = CharField(db_column="status", default="")  #

    class Meta:
        db_table = 'task'
Exemplo n.º 23
0
class Tag(Model):
    """Class to save Journal Entry Tags"""
    tag = CharField(unique=True)
    journal_entries = ManyToManyField(JournalEntry, related_name='tags')

    class Meta:
        database = DATABASE

    @classmethod
    def create_tag(cls, tag):
        try:
            with DATABASE.transaction():
                cls.create(tag=tag)
        except IntegrityError:
            raise ValueError("Tag already exists")
Exemplo n.º 24
0
class Message(database.db.basemodel):
    user = ForeignKeyField(User, related_name='messages')
    #message = AESEncryptedField(conf.get_config("taemin").get("aes_password", "banane").encode("utf-8"))
    message = TextField()
    key = TextField(null=True)
    value = TextField(null=True)
    target = TextField(null=True)
    chan = ForeignKeyField(Chan, related_name='messages', null=True)
    link = ForeignKeyField(Link,
                           related_name='messages',
                           null=True,
                           on_delete='SET NULL')
    highlights = ManyToManyField(User, related_name='hl')

    created_at = DateTimeField(default=datetime.datetime.now)
Exemplo n.º 25
0
class Tweet(BaseModel):
    """
    Tweet model.
    Stores the tweet's unique ID as a primary key along with the user, text and date.
    """
    id = peewee.BigIntegerField(unique=True, primary_key=True)
    user = peewee.ForeignKeyField(User, related_name='tweets')
    text = peewee.CharField()
    date = peewee.DateTimeField()
    tags = ManyToManyField(Hashtag)
    urls = ManyToManyField(URL)
    mentions = ManyToManyField(User)
    media = ManyToManyField(Media)
    searchterm = peewee.CharField()
    place = peewee.ForeignKeyField(Place, null=True)  # field is called _id
    reply_to_user = peewee.ForeignKeyField(User,
                                           null=True,
                                           related_name='replies')
    reply_to_tweet = peewee.BigIntegerField(null=True)
    retweet = peewee.ForeignKeyField('self',
                                     null=True,
                                     related_name='retweets')
    lat = peewee.FloatField(null=True)
    lon = peewee.FloatField(null=True)
Exemplo n.º 26
0
class Stop(Model):
    id = PrimaryKeyField()
    stop_id = BigIntegerField(null=False)
    name = CharField(null=False)
    lat = FloatField(null=False)
    lng = FloatField(null=False)
    timezone = CharField(max_length=100, null=True)
    feed = ForeignKeyField(Feed, null=False, related_name='stops')
    routes = ManyToManyField(Route, related_name='stops')

    def __str__(self) -> str:
        return '{s.id} - {s.stop_id} ({s.name})'.format(s=self)

    @classmethod
    def get_nearby(cls, lat, lng, distance):
        cursor = db.execute_sql(
            '''
                        SELECT
                            stop.id AS id,
                            %(distance_unit)s * DEGREES(ACOS(COS(RADIANS(%(lat)s))
                                             * COS(RADIANS(stop.lat))
                                             * COS(RADIANS(%(lng)s - stop.lng))
                                             + SIN(RADIANS(%(lat)s))
                                             * SIN(RADIANS(stop.lat)))) AS distance
                        FROM stop

                        WHERE stop.lat
                              BETWEEN %(lat)s - (%(radius)s / %(distance_unit)s)
                              AND %(lat)s + (%(radius)s / %(distance_unit)s)
                              AND stop.lng
                              BETWEEN %(lng)s - (%(radius)s / (%(distance_unit)s * COS(RADIANS(%(lat)s))))
                              AND %(lng)s + (%(radius)s / (%(distance_unit)s * COS(RADIANS(%(lat)s))))
                    ''', {
                "lat": lat,
                "lng": lng,
                "radius": distance / 1000,
                "distance_unit": 111.045,
            })

        result = []

        for nearby in cursor.fetchall():
            result.append(cls.get(id=nearby[0]))

        return result

    class Meta:
        database = db
Exemplo n.º 27
0
class Road(BaseModel):
    """
    货道
    """
    id = pw.PrimaryKeyField()
    no = pw.CharField()                                 # 编号
    device = pw.ForeignKeyField(Device)                 # 对应的设备
    amount = pw.IntegerField(default=0)                 # 商品剩余数量
    status = pw.IntegerField(default=RoadStatus.SELLING)                 # 货道状态:取值定义请看const
    item = pw.ForeignKeyField(Item, null=True)         # 绑定的商品
    thumbnails = ManyToManyField(Image, related_name="roads")
    price = pw.IntegerField(default=0)                                # 出售价格
    fault = pw.IntegerField(default=FaultType.NONE, index=True)
    fault_at = pw.DateTimeField(null=True)
    updated_at = pw.DateTimeField(default=dte.now)
    created_at = pw.DateTimeField(default=dte.now)      # 创建时间

    class Meta:
        db_table = 'road'

        indexes = (
            (('device', 'no'), True),
        )

    @property
    def status_msg(self):
        return RoadStatusMsg[self.status]

    @property
    def fault_msg(self):
        return FaultMsg[self.fault]

    @property
    def sale_price(self):
        return self.price or getattr(self.item, "basic_price", 0)

    @property
    def sale_image_url(self):
        images = getattr(self, "thumbnails", []) or getattr(self.item, "thumbnails", [])
        return images[0].url if images else ""
Exemplo n.º 28
0
class CSSubmissionCable(BaseModel):
    """CSSubmissionCable model. Communicate what patch submit to ambassador"""

    cs = ForeignKeyField(ChallengeSet, related_name='submission_cables')
    ids = ForeignKeyField(IDSRule, related_name='submission_cables')
    cbns = ManyToManyField(ChallengeBinaryNode,
                           related_name='submission_cables')
    round = ForeignKeyField(Round, related_name='cs_submission_cables')
    processed_at = DateTimeField(null=True)

    @classmethod
    def create(cls, *args, **kwargs):
        if 'cbns' in kwargs:
            cbns = kwargs.pop('cbns')

        obj = super(cls, cls).create(*args, **kwargs)
        obj.cbns = cbns
        return obj

    @classmethod
    def get_or_create(cls, cs, ids, round, cbns=None):  # pylint: disable=arguments-differ
        if cbns is None:
            cbns = []
        results = cls.select() \
                     .where((cls.cs == cs)
                            & (cls.ids == ids)
                            & (cls.round == round))
        for cssb in results:
            found = {cbn.id for cbn in cssb.cbns}
            expected = {cbn.id for cbn in cbns}
            if (len(found) == len(expected)) and \
               (len(found & expected) == len(expected)):
                return (cssb, False)
        return (cls.create(cs=cs, ids=ids, cbns=cbns, round=round), True)

    def process(self):
        self.processed_at = datetime.now()
        self.save()
Exemplo n.º 29
0
class Item(BaseModel):
    """
    商品
    """
    id = pw.PrimaryKeyField()
    no = pw.CharField(default="")                       # 商品编码;商品编号
    category = pw.ForeignKeyField(ItemCategory)         # 商品类型
    brand = pw.ForeignKeyField(ItemBrand)               # 商品品牌
    name = pw.CharField(null=True, unique=True, index=True)          # 商品名称
    thumbnails = ManyToManyField(Image, related_name="items")
    basic_price = pw.IntegerField(default=0)            # 价格;建议价; 并不是最终出售价格
    cost_price = pw.IntegerField(default=0)             # 成本价
    description = pw.CharField(null=True)               # 商品描述
    updated_at = pw.DateTimeField(default=dte.now)
    created_at = pw.DateTimeField(default=dte.now)

    class Meta:
        db_table = 'item'

    def to_dict(self, base_url=""):
        pv = self.order_set.count()
        sales = self.order_set.where(Order.status == C.OrderStatus.DONE).count()
        return {
            "id": self.id,
            "no": self.no,
            "sales": sales,         # 销量
            "pv": pv,               # 访问量
            "name": self.name,
            "category": self.category.to_dict(base_url=base_url),
            "brand": self.brand.to_dict() if self.brand else {},
            "basicPrice": self.basic_price,
            "costPrice": self.cost_price,
            "createdAt": self.created_at.strftime("%Y-%m-%d %H:%M:%S"),
            "updatedAt": self.updated_at.strftime("%Y-%m-%d %H:%M:%S"),
            "thumbnails": [obj.to_dict(base_url=base_url)
                           for obj in self.thumbnails]
        }
Exemplo n.º 30
0
class Service(ConnectionModel):
    name = orm.CharField(max_length=255)
    item = orm.ForeignKeyField(Item, related_name='items')
    pub_date = orm.DateTimeField(default=datetime.datetime.now)
    allowed_users = ManyToManyField(User, related_name='allowed_services')

    # Password
    username = orm.CharField(max_length=255, null=True)
    password = orm.CharField(max_length=255, null=True)
    url = orm.CharField(max_length=255, null=True)
    port = orm.IntegerField(null=True)
    extra = orm.TextField(null=True)

    # SSH
    ssh_title = orm.CharField(max_length=255, null=True)
    ssh_public = orm.TextField(null=True)
    ssh_private = orm.TextField(null=True)

    # SSL
    ssl_title = orm.CharField(max_length=255, null=True)
    ssl_filename = orm.CharField(max_length=255, null=True)

    # Other
    other = orm.TextField(null=True)