예제 #1
0
class Course(db.Document):
    """Modeling of a course object. 
    course_id:          integer
    title:              string
    year:               integer
    description:        string
    prerequisites:      list(integer), list of course ids
    instructor:         integer, instructor's user id
    enrolled_students:  list of students' user ids
    time_added:         datetime, 
                        timestamp of the course added to the system
    start_date:         datetime 
    end_date:           datetime
    recurring:          boolean, is a recurring course (or not)
    announcements:      list of announcements
    """

    course_id = db.IntField(required=True)
    #code = db.StringField(max_length=20)
    title = db.StringField(max_length=60, required=True)
    year = db.IntField(required=True)
    description = db.StringField(required=True)
    prerequisites = db.ListField(db.IntField())
    instructor = db.IntField(required=True)
    #school = db.StringField(max_length=60)
    enrolled_students = db.ListField(db.IntField())
    time_added = db.DateTimeField(default=datetime.now())
    start_date = db.DateTimeField(required=True)
    end_date = db.DateTimeField(required=True)
    recurring = db.BooleanField(required=True)
    announcements = db.ListField(db.EmbeddedDocumentField(Announcement))
class Api(db.Document):
    # 字段
    api_name = db.StringField()  # 服务名称
    api_description = db.StringField()  # 服务描述
    api_id = db.SequenceField()  # 服务唯一标示
    url = db.URLField()  # 自身已经封装成的可以调用的url地址
    api_url = db.URLField()  # 转接url地址

    img_link = db.URLField()
    json_link = db.URLField()

    api_crawl_rules_link = db.URLField()  # 爬虫规则列表链接

    candidate = db.ListField()  # api参数列表

    main_sec_id = db.IntField()

    api_network = db.ListField()  # 网页可能有效的network请求

    api_result_example = db.ListField()

    form_rules_link = db.URLField()  # check click button的json链接

    api_request_parameters_candidate = db.ListField()  # 调用服务时可以使用的参数

    # {"type":"text",
    #  "query_name":"",
    #  "required":false/true, 是否必须
    #  "level":0/1/2,   0-系统级(__max_page),1-查询级(需要填充到输入框中的),2-返回级(返回参数中的)
    #   "example":
    #   "description"
    # }

    def __str__(self):
        return "service:{} - url:{}".format(self.api_name, self.url)
예제 #3
0
class OrderStatus(db.Document):
    """"""
    meta = {
        'db_alias': 'db_order',
        'indexes': ['user_id'],
    }
    user_id = db.ObjectIdField(required=True)
    orders = db.ListField(db.ReferenceField('Order'))
    items = db.ListField(db.IntField())
    total = db.FloatField(default=0)
    received = db.FloatField(default=0)
    num_orders = db.IntField(default=0)
    num_unpaid = db.IntField(default=0)
    num_waiting = db.IntField(default=0)

    def clean(self):
        for field in ('total', 'received', 'num_orders', 'num_unpaid',
                      'num_waiting'):
            if getattr(self, field, 0) < 0:
                setattr(self, field, 0)

    @classmethod
    def by_user(cls, user_id):
        cls.objects(user_id=user_id).update_one(set__user_id=user_id,
                                                upsert=True)
        return cls.objects(user_id=user_id).first()
예제 #4
0
class Image(db.Document):
    meta = {
        'collection': 'image',
        'ordering': ['-img_id'],
        'strict': False,
    }
    img_id = db.IntField()
    url = db.ListField(db.StringField())
    word = db.StringField(max_length=512)
    author = db.StringField()
    board = db.StringField()
    w_list = db.ListField(db.StringField())
    m_list = db.ListField(db.StringField())
    w = db.IntField(default=0)
    m = db.IntField(default=0)
    comments = db.ListField(db.EmbeddedDocumentField(Comment))
    visible = db.BooleanField()
    ct = db.DateTimeField(default=datetime.now)

    def api_data(self):
        return dict(
            img_id=self.img_id,
            url=self.url,
            word=self.word,
            author=self.author,
            w=self.w,
            m=self.m,
            ct=self.ct.__str__(),
            comments_num=len(self.comments),
        )
예제 #5
0
class BestArticles(db.Document):
    user = db.ReferenceField('User')
    key = db.StringField()
    articles = db.ListField(db.StringField())
    discarted = db.ListField(db.StringField())
    timestamp = db.DateTimeField(default=datetime.datetime.now)
    remarks = db.StringField(default="")
예제 #6
0
class Job(db.DynamicDocument):
    task_information = db.StringField()

    model_file = db.StringField()
    model_meta_file = db.StringField()

    vocabulary = db.StringField()
    num_training_examples_in_model = db.IntField()

    checkpoints = db.DictField()

    current_hit_ids = db.ListField()

    status = db.StringField()

    control_strategy = db.StringField()

    experiment_id = db.StringField()

    mturk_connection = db.StringField()

    exceptions = db.ListField()

    control_data = db.StringField()

    logging_data = db.StringField()
예제 #7
0
class Post(db.Document):
    """Post collection with its comments"""
    meta = {'collection': 'post'}
    title = db.StringField(required=True)
    body = db.StringField()
    author = db.ReferenceField(User)
    comments = db.ListField()
    tags = db.ListField(StringField(), default=list)
    createdAt = db.DateTimeField(default=datetime.utcnow)
    modified = db.BooleanField(default=False)
    lastModifiedAt = db.DateTimeField(default=datetime.utcnow)

    def update_last_modified(self):
        if not self.modified:
            self.modified = True
        self.lastModifiedAt = datetime.utcnow

    def get_author(self):
        return self.author

    def to_json(self):
        data = self.to_mongo()
        data["author"] = {
            "username": self.author.username,
            "avatar_url": self.author.avatar_url
        }
        return data
예제 #8
0
파일: models.py 프로젝트: 29furkhan/bakery
class Shop(db.Document):
    title = db.StringField()
    description = db.StringField()
    discount = db.StringField()
    welcome = db.StringField()
    history = db.StringField()
    why = db.StringField()
    reasons = db.ListField(db.ListField(db.StringField()))
예제 #9
0
class GradeBook(db.EmbeddedDocument):
  '''
  The gradebook class is designed to contain all the information regarding
  grades for a course. Each Course has one Gradebook. A gradebook can group
  columns together with groups and groups are either for assignments or
  auxillary grades.
  '''

  assignmentGrades = db.ListField(db.ReferenceField('GBGroup'))
  auxillaryGrades = db.ListField(db.ReferenceField('GBGroup'))

  def getCategoryByName(self, name):
    for c in self.categories:
      if c.name == name:
        return c
    return None

  def cleanup(self):
    for c in self.categories:
      c.cleanup()

  def groups(self):
    for a in self.assignmentGrades:
      yield a
    for a in self.auxillaryGrades:
      yield a

  def columns(self):
    for a in self.assignmentGrades:
      if len(a.columns) == 0:
        yield None
      else:
        for c in sorted(a.columns, key=lambda x: x.name):
          yield c
    for a in self.auxillaryGrades:
      if len(a.columns) == 0:
        yield None
      else:
        for c in a.columns:
          yield c

  def columnsForAssignment(self, assignmentNum):
    if (assignmentNum >= len(self.assignmentGrades)):
      yield None
    
    else:
      a = self.assignmentGrades[assignmentNum]
      for c in sorted(a.columns, key=lambda x: x.name):
        yield c

  def totalPoints(self):
    points = 0
    for c in self.columns():
      if c == None:
        continue
      points += c.maxScore

    return points
예제 #10
0
class Tip(db.Document):
    """
    Represents the definition of a tip in the
    repository.

    Fields:
    tip_name                Name of the tip. Required.
                                    takes a string.

    description             Brief description of the tip. Required.
                                    takes a string

    difficulty              Level of difficulty for the tip. Required.
                                    takes a string: 'beginner', 'intermediate', or 'advanced'

    media_type              Type of supplemental media. Required.
                                    takes a string: 'No Supplemental Media', 'Video', or 'Audio

    media_url               Audio component. Optional.
                                    takes a string.

    video_id                ID of a youtube video, used to embed. Optional.
                                    takes a string.

    submitter               Name of the submitter. Required.
                                    takes a string

    equipment               Names of equipment that might relate to this tip. Optional.
                                    takes a list of strings

    ingredients             Names of ingredients that might relate to this tip. Optional.
                                    takes a list of strings

    techniques              Names of techniques that might relate to this tip. Optional.
                                    takes a list of strings

    instructions            Main text of the tip.
                                    takes a string

    tags                    List of the categories it falls into
                                    takes a list of strings (method, ingredient, equipment)
    """
    query_class = TipQuery
    tip_name = db.StringField(required=True)
    description = db.StringField(required=True)
    difficulty = db.StringField(required=True)
    media_type = db.StringField(required=True)
    media_url = db.StringField(required=False)
    video_id = db.StringField(required=False)
    submitter = db.StringField(required=False)
    equipment = db.ListField(db.StringField(required=False), required=False)
    ingredients = db.ListField(db.StringField(required=False), required=False)
    techniques = db.ListField(db.StringField(required=False), required=False)
    instructions = db.ListField(db.StringField(required=False), required=False)
    tags = db.ListField(db.StringField(required=False), required=False)

    def get_id(self):
        return str(self.mongo_id)
예제 #11
0
class Seller2Products(db.Document):
    seller_id = db.IntField(required=True)
    product_ids = db.ListField(db.IntField())
    archive_product_ids = db.ListField(db.IntField())

    meta = {'collection': 'map_seller_to_products', 'indexes': ['seller_id']}

    def __repr__(self):
        return f'Seller(id={self.id})'
예제 #12
0
class Monitorados(db.Document):
    meta = {'collection': 'Monitorados'}
    cod_audio = db.StringField(required=True)
    cod_usu = db.StringField(required=True)
    datahora = db.DateTimeField()
    total_ptpositivo = db.IntField(required=True)
    total_ptnegativo = db.IntField(required=True)
    sentditas = db.ListField(db.EmbeddedDocumentField(sentDitas))
    sentnditas = db.ListField(db.EmbeddedDocumentField(sentNDitas))
예제 #13
0
class ImgParam(db.Document):

    type = db.StringField(required=True)
    name = db.StringField(required=True)
    value = db.ListField()
    limit = db.StringField()
    pName = db.StringField()
    desc = db.StringField()
    valueDesc = db.ListField()
예제 #14
0
class Information(db.Document):
    user_id = db.ReferenceField(User, unique=True, required=True)
    history = db.ListField(db.EmbeddedDocumentField(History), default=list)
    like = db.ListField(db.ReferenceField(Product, required=True),
                        default=list)
    cart = db.ListField(db.ReferenceField(Product, required=True),
                        default=list)
    coupon = db.ListField(db.ReferenceField(Coupon, required=True),
                          default=list)
예제 #15
0
class Projects(db.Document):

	author = db.GenericReferenceField(db_field='au', verbose_name='Autor')
	title = db.StringField(db_field='tl', verbose_name='Titlu')
	content = db.StringField(db_field='ct', verbose_name='Descriere', required=True)
	timestamp = db.DateTimeField(db_field='ts', verbose_name='Data')
	posts = db.ListField(db.GenericReferenceField(), db_field='ps',verbose_name='Postari')
	members = db.ListField(db.GenericReferenceField(), db_field='mb', verbose_name='Participanti')
	applicants = db.ListField(db.GenericReferenceField(), db_field='ap', verbose_name='Aplicatii')
예제 #16
0
class SongRoom(db.Document):
    name = db.StringField()
    host = db.ReferenceField('User')

    members = db.ListField(db.ReferenceField('User'))
    queue = db.ReferenceField('SongQueue')
    playing = db.ReferenceField('Song')
    history = db.ListField(db.ReferenceField('Song'))

    location = db.PointField()
예제 #17
0
class OptimizeModel(db.DynamicDocument):
    question_num = db.IntField(min_value=0, default=-1)
    wordbase = db.DictField(default={})
    weights = db.DictField(default={})
    key_history_cost = db.ListField(db.FloatField(default=0))
    detail_history_cost = db.ListField(db.FloatField(default=0))
    complete_time = db.DateTimeField(
        default=lambda: datetime.datetime.utcnow())
    finish = db.BooleanField(default=True)
    meta = {'collection': 'optimize'}
예제 #18
0
class User(db.Document):
    # 字段
    name = db.StringField(max_length=30, required=True)
    password = db.StringField(max_length=30, min_length=6, required=True)
    phone = db.StringField()
    device = db.ReferenceField(Device1)
    devices = db.ListField(db.ReferenceField(Device1))
    emdevices = db.ListField(db.EmbeddedDocumentField('Device1'))

    def __str__(self):
        return "name:{} - phone:{}".format(self.name, self.phone)
예제 #19
0
class NodeData(db.Document):
    # 字段
    nodeList = db.ListField(db.StringField(max_length=30))
    linkList = db.ListField(db.StringField(max_length=30))
    attr = db.StringField()
    config = db.StringField()
    status = db.StringField()
    remarks = db.ListField(db.StringField(max_length=30))

    def __str__(self):
        return "nodeList:{} - linkList:{}".format(self.nodeList, self.linkList)
예제 #20
0
class Artist(db.Document):
    name = db.StringField(unique=True)
    description = db.StringField()
    location = db.ReferenceField(Location)
    genre = db.ListField(db.ReferenceField(Genre))
    members = db.ListField(db.ReferenceField(User))
    followers = db.ListField(db.ReferenceField(User))
    tracks = db.ListField(db.ReferenceField(Track))

    def __repr__(self):
        return '<Artist {}>'.format(self.name)
예제 #21
0
class Article(gj.Document, db.Document):

    url = db.URLField()
    author = db.StringField(default="")
    chuncks = db.ListField(db.StringField(),
                           default=list,
                           exclude_to_json=True)
    content = db.StringField(default="")
    domain = db.StringField(default="")
    title = db.StringField(default="")
    created_at = db.DateTimeField(default=datetime.datetime.utcnow)
    updated_at = db.DateTimeField(default=datetime.datetime.utcnow)
    image = db.URLField(required=False)
    # owner = None
    status = db.IntField(default=0, min_value=0, max_value=3)
    likes = db.ListField(db.ReferenceField("User"),
                         default=list,
                         exclude_to_json=True)

    meta = {
        "collection": "article",
        "indexes": [
            "url",
            "$url",  # text index
            "#url",  # hashed index
        ],
        "strict": False,
    }

    @property
    def likes_count(self) -> int:
        return len(self.likes) if self.likes else 0

    def check_like(self, user) -> bool:
        return user and user in self.likes

    def json(self, user=None):
        data = {
            **json.loads(self.to_json()),
            "likes_count": self.likes_count,
            "content": self.content[:100] if self.content else "",
            "like": 1 if user and self.check_like(user) else 0,
            "audios":
            [f"/media/{self.id}/full.mp3"] if self.status == 1 else [],
            # check if user already added article
            "added": 1 if user and self.check_added(user) else 0,
        }

        return data

    def check_added(self, user) -> bool:
        ua = UserArticle.objects(user=user, article=self)
        return True if ua else False
예제 #22
0
class AnalysisModel(db.DynamicDocument):
    question_num = db.IntField(min_value=0, default=-1)
    exam_id = db.StringField(max_length=32)
    question_id = db.StringField(max_length=32)
    score_detail = db.FloatField(default=0, min_value=0)
    score_key = db.FloatField(default=0, min_value=0)
    voice_features = db.DictField(default={})
    key_hits = db.ListField(db.FloatField(default=0))
    detail_hits = db.ListField(db.ListField(db.FloatField(default=0)))
    user = db.ObjectIdField()
    date = db.DateTimeField()

    meta = {'collection': 'analysis'}
예제 #23
0
class Questions(db.Document):

    _id = db.IntField(primary_key=True)
    url = db.URLField()
    title = db.StringField()
    content = db.StringField()
    is_solved = db.BooleanField(default=0)
    answer_count = db.IntField()
    view_count = db.StringField()
    vote_count = db.StringField()
    tags = db.ListField()
    answers = db.ListField()
    source = db.StringField()
예제 #24
0
class User(db.Document):
    meta = {'collection': 'user'}
    email = db.StringField(max_length=100, unique=True)
    id_auth = db.StringField(max_length=50)
    customer_name = db.StringField(max_length=50)
    created_at = db.DateTimeField(default=datetime.datetime.utcnow)
    updated_at = db.DateTimeField(default=datetime.datetime.utcnow)
    birthdate = db.DateTimeField()
    role = db.StringField(max_length=255, default="admin")
    language = db.StringField(max_length=255, default="french")
    favorite_genres = db.ListField(db.StringField(), default=[])
    watched_movies = db.ListField(db.StringField(), default=[])
    my_list = db.ListField(db.StringField(), default=[])
예제 #25
0
class GameRoom(db.Document):
    word = db.StringField(default="")
    waiting = db.BooleanField(default=True)
    currentQuestion = db.StringField(default="")
    gameFinished = db.BooleanField(default=False)
    winner = db.ListField(db.StringField())
    bothAnswered = db.BooleanField(default=False)
    members = db.ListField(db.EmbeddedDocumentField(Player),default=list)
    answers = db.ListField(db.EmbeddedDocumentField(PlayerAnswer))
    questions = db.ListField(db.StringField())
    hasBot = db.BooleanField(default=False)
    botName = db.StringField(default="")
    created_at = db.DateTimeField(default=datetime.datetime.utcnow)
예제 #26
0
class Post(db.Document):
    title = db.StringField(max_length=120, required=True)
    slug = db.StringField(max_length=64, unique=True)
    # ReferenceField 是引用字段,在数据库中真正存储的是 ObjectID
    # reverse_delete_rule=db.CASCADE 定义了,author 这个引用字段当被引用的对象删除时,它如何处理
    # 比如 author 引用了用户 ross,当我们删除 ross 时,由于定义了 db.CASCADE,所以会 [级联删除] ross 用户所发表过的所有 Post 文章
    author = db.ReferenceField(User, reverse_delete_rule=db.CASCADE)
    category = db.ReferenceField(Category, reverse_delete_rule=db.NULLIFY)
    # ListField 表明它是一个列表,可以保存多个其它类型的字段值,比如 StringField、ReferenceField、EmbeddedDocumentField 都可以
    tags = db.ListField(db.ReferenceField(Tag, reverse_delete_rule=db.PULL))
    comments = db.ListField(db.EmbeddedDocumentField(Comment))
    # 创建的时间,建议在数据库中全部存储 UTC 时间
    # default=datetime.utcnow 表明不指定此字段的值时,它会默认保存当前的时间
    created_at = db.DateTimeField(default=datetime.utcnow)
    # 价格。需要数学计算时,请使用 DecimalField,不要用 FloatField (计算结果不对)
    price = db.DecimalField(default='0.00')
    # 是否发布
    published = db.BooleanField(default=True)

    meta = {
        'allow_inheritance': True,  # 允许被继承,比如下面的 TextPost 就继承自 Post
        'indexes': ['title', 'author'],  # 索引字段,后续按这两个字段值查询时可以加快速度
        'ordering': ['-created_at']  # 表示按 created_at 降序排列,没有减号表示升序排列
    }

    @queryset_manager
    def live_posts(doc_cls, queryset):
        '''非默认的objects查询集,此查询集只返回发布状态为True的博客文章'''
        return queryset.filter(published=True)

    def clean(self):
        '''
        MongoEngine allows you to create custom cleaning rules for your documents when calling save().
        By providing a custom clean() method you can do any pre validation / data cleaning.
        '''
        # 如果创建Post对象时没有提供slug,则根据title自动生成;如果提供了slug,用slugify再清理
        if self.slug:
            self.slug = slugify(self.slug)
        else:
            self.slug = slugify(self.title)
        # 判断slug是否唯一
        filters = dict(slug=self.slug)
        if self.id:
            filters['id__ne'] = self.id
        # 不能用 exist = self.__class__.objects(**filters),因为可能创建 TextPost 对象时,其它子类有相同的 slug
        exist = Post.objects(**filters)
        if exist.count():
            self.slug = "{0}-{1}".format(self.slug, random.getrandbits(32))

    def __str__(self):
        return self.title
예제 #27
0
class LogisticProvider(db.Document, WeightPrice):
    meta = {
        'db_alias': 'db_order',
    }
    name = db.StringField()
    display_name = db.StringField()
    description = db.StringField()
    service_intro = db.DictField()
    logo = db.StringField()
    country = db.StringField()
    is_active = db.BooleanField(default=False)

    rule_desc = db.StringField()
    init_price = db.FloatField(required=True)
    init_weight = db.IntField(required=True)
    continued_price = db.FloatField(required=True)
    continued_weight = db.FloatField(required=True)
    init_coin = db.IntField(default=0)

    features = db.ListField(db.StringField())
    promotion = db.StringField(default='')

    limited_weight = db.IntField(required=True)
    limited_category = db.ListField(db.StringField())
    is_recommended = db.BooleanField(default=False)

    rating = db.DecimalField(precision=1)
    rating_users = db.IntField()

    def __repr__(self):
        return '<LogisticProvider {}>'.format(self.name)

    @classmethod
    def get_provider_shipping(cls, logistic_name, country, weight):
        if not logistic_name:
            logistic_name = 'default'
        provider = cls.objects(name=logistic_name, country=country).first()
        return provider.get_shipping(weight)

    @queryset_manager
    def active(doc_cls, queryset):
        return queryset.filter(is_active=True)

    def to_json(self):
        return dict(
            name=self.name,
            display_name=self.display_name,
            service_intro=self.service_intro,
            desc=self.description,
        )
class Recipe(db.Document):
    query_class = Queries
    title = db.StringField()
    filename = db.StringField()
    ingredients = db.ListField(db.StringField())
    tags = db.ListField(db.StringField())

    def toJson(self):
        json = {}
        json['title'] = self.title
        json['filename'] = self.filename
        json['ingredients'] = self.ingredients
        json['tags'] = self.tags
        return json
예제 #29
0
파일: models.py 프로젝트: ai001/TimeLottery
class UserActivity(db.EmbeddedDocument):
    created = db.DateTimeField(default=lambda: now())
    email_verification = db.EmbeddedDocumentField(EmailVerification,
                                                  default=EmailVerification)
    password_reset = db.EmbeddedDocumentField(PasswordReset,
                                              default=PasswordReset)
    user_restricted = db.BooleanField(default=False)
    failed_logins = db.IntField(default=0)
    user_banned = db.BooleanField(default=False)
    valid_tokens = db.ListField()
    payment_reference = db.StringField(min_length=UID_SIZE,
                                       max_length=UID_SIZE,
                                       unique=True)
    activity_audit = db.ListField(db.ReferenceField(ActivityAudit))
예제 #30
0
파일: Resource.py 프로젝트: voidf/sher_oa3
class Resource(db.Document):
    name = db.StringField()
    password = db.StringField(default='')
    last_modify = db.DateTimeField()
    create_datetime = db.DateTimeField()
    writable = db.ListField(db.ReferenceField(UserBase, reverse_delete_rule=4))
    readable = db.ListField(db.ReferenceField(UserBase, reverse_delete_rule=4))
    meta = {'allow_inheritance': True}

    def rename(self, new_name: str) -> self:
        self.name = new_name
        self.last_modify = datetime.datetime.now()
        return self.save()

    def set_password(self, password: str) -> self:
        self.password = password
        return self.save()

    def new_resource(author: UserBase):
        return Resource(writable=[author],
                        readable=[author],
                        last_modify=datetime.datetime.now())

    def append_access(self, new_writables=[], new_readables=[]):
        for _ in new_writables:
            self.update(add_to_set__writable=_)
        for _ in new_readables:
            self.update(add_to_set__readable=_)
        return

    def discard_access(self, ban_writables=[], ban_readables=[]):
        for _ in ban_writables:
            self.update(pull__writable=_)
        for _ in ban_readables:
            self.update(pull__readable=_)
        return

    def modify_access(self, new_writables=[], new_readables=[]):
        self.writable = new_writables
        self.readable = new_readables
        return self.save()

    def get_base_info(self) -> dict:
        return {
            "id": str(self.id),
            "name": self.name,
            "last_modify": self.last_modify,
            "create_datetime": self.create_datetime
        }