コード例 #1
0
class TestDoc(Document):

    int1 = IntField()
    str1 = StringField()
    str2 = StringField()
    str3 = StringField(db_field='str_3_db_name')

    index_1 = Index().ascending(int1).descending(str3)
    index_2 = Index().descending(str3)
    index_3 = Index().descending('str2').unique()
    index_4 = Index().descending('str1').unique(drop_dups=True)
コード例 #2
0
ファイル: test_index.py プロジェクト: yinpeng/MongoAlchemy
class TestDoc(Document):

    int1 = IntField()
    str1 = StringField()
    str2 = StringField()
    str3 = StringField()

    index_1 = Index().ascending('int1').descending('str3')
    index_2 = Index().descending('str3')
    index_3 = Index().descending('str2').unique()
    index_4 = Index().descending('str1').unique(drop_dups=True)
コード例 #3
0
class User(UserMixin, db.Document):
    username = db.StringField(required=True)
    username_index = Index().ascending('username').unique()
    hashed_password = db.StringField(required=True)
    email = db.StringField()
    email_index = Index().ascending('email').unique()
    first_name = db.StringField()
    last_name = db.StringField()

    def get_id(self):
        return str(self.mongo_id)
コード例 #4
0
class Groups(ma.Document):

    name = ma.StringField(required=True)
    description = ma.StringField()
    member_refs = ma.ListField(ma.RefField('Users'),
                               required=False,
                               allow_none=True,
                               ignore_missing=True,
                               default_empty=True)
    members = member_refs.rel(ignore_missing=True)

    # link to info page
    @property
    def link(self):
        return "/groups/{}".format(self.mongo_id)

    @property
    def render(self):
        return '<a href="{}">{}</a>'.format(self.link, self.name)

    # relationships
    @property
    def servers(self):
        group_ref = DBRef('Groups', ObjectId(self.mongo_id))
        return Servers.query.filter(Servers.group_ref == group_ref).all()

    # magic methods
    def __repr__(self):
        return "<Groups {}>".format(self.name)

    def __str__(self):
        return str(self.name)

    # indexes
    name_index = Index().ascending('name').unique()
コード例 #5
0
class T(Document):
    i = IntField()
    j = IntField(required=False)
    s = StringField(required=False)
    l = ListField(IntField(), required=False)
    a = IntField(required=False, db_field='aa')
    index = Index().ascending('i')
コード例 #6
0
class Switches(ma.Document):

    id = ma.StringField(required=True)
    # model
    model_ref = ma.RefField('SwitchModels')
    model = model_ref.rel()
    name = ma.StringField(required=False, allow_none=True)
    # group
    group_ref = ma.RefField('Groups', allow_none=True, ignore_missing=True)
    group = group_ref.rel(allow_none=True)
    # location
    location_ref = ma.RefField(required=False,
                               validator=_validate_location,
                               allow_none=True,
                               ignore_missing=True)
    location = location_ref.rel(allow_none=True)

    # properties
    @property
    def link(self):
        return '/switches/{}'.format(self.id)

    @property
    def management_link(self):
        if self.management:
            if self.management.link:
                return str(self.management.link)
            elif self.management.link:
                return self.management.link

    # indexes
    id_index = Index().ascending('id').unique()
コード例 #7
0
class Rooms(ma.Document):

    # parameters
    name = ma.StringField()
    type_ref = ma.RefField('RoomTypes')
    type = type_ref.rel()
    description = ma.StringField()

    # link to info page
    @property
    def link(self):
        return "/rooms/{}".format(self.mongo_id)

    @property
    def render(self):
        return '<a href="{}">{}</a>'.format(self.link, self.name)

    # magic methods
    def __str__(self):
        return str(self.name)

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

    # indexes
    name_index = Index().ascending('name').unique()
コード例 #8
0
class Memory(ma.Document):

    # parameters
    model_ref = ma.RefField('MemoryModels')
    serial_number = ma.StringField(allow_none=True)

    # indexes
    sn_index = Index().ascending('serial_number').unique()
コード例 #9
0
ファイル: models.py プロジェクト: jianfang/cloudstore
class Idol(db.Document):
    # fields
    id = db.IntField()
    name = db.StringField()
    stage_name = db.StringField()
    birthday = db.DateTimeField()
    time_added = db.CreatedField()
    avatar = db.StringField()
    last_posted = db.DateTimeField()

    # optional fields
    posts = db.ListField(db.SRefField(Post), default_empty=True)
    followers = db.ListField(db.SRefField(User), default_empty=True)

    # index
    name_index = Index().descending('name').unique()

    @staticmethod
    def add_idol(name, stage_name, birthday, avatar):
        id = 0
        date_object = datetime.strptime(birthday, '%Y/%m/%d')
        idol = Idol(id=id,
                    name=name,
                    stage_name=stage_name,
                    birthday=date_object,
                    avatar=avatar)
        idol.save()
        return idol

    @staticmethod
    def validate_idol(name):
        if Idol.query.filter_by(name=name).first():
            raise ValidationError('Idol already exists.',
                                  'IDOL_ALREADY_EXISTS')

    @staticmethod
    def get_idol(id):
        iid = ObjectId(str(id))
        idol = Idol.query.filter(Idol.mongo_id == iid).first()
        return idol

    def add_post(self, post):
        self.posts.append(post.mongo_id)
        self.last_posted = datetime.utcnow()
        self.save()

    def to_json(self):
        json_idol = {
            'id': str(self.mongo_id),
            'url': url_for('api.get_idol',
                           id=str(self.mongo_id),
                           _external=True),
            'name': self.name,
            'stage_name': self.stage_name,
            'follower_count': len(self.followers),
            'avatar': self.avatar
        }
        return json_idol
コード例 #10
0
class Projects(ma.Document):

    # parameters
    owner_ref = ma.RefField('Users')
    owner = owner_ref.rel()
    group_ref = ma.RefField('Groups')
    group = group_ref.rel()
    name = ma.StringField()
    description = ma.StringField(allow_none=True,
                                 ignore_missing=True,
                                 required=False)
    created_on = ma.CreatedField(tz_aware=True)
    modified_on = ma.ModifiedField(tz_aware=True)
    start_date = DateField(ignore_missing=True,
                           allow_none=True,
                           required=False)
    target_end_date = DateField(ignore_missing=True,
                                allow_none=True,
                                required=False)
    status_ref = ma.RefField('ProjectStatusTypes',
                             allow_none=True,
                             ignore_missing=True)
    status = status_ref.rel(allow_none=True)
    updates = ma.ListField(ma.DocumentField('ProjectUpdates'),
                           required=False,
                           allow_none=True,
                           default_empty=True)
    member_refs = ma.ListField(ma.RefField('Users'),
                               required=False,
                               default_empty=True,
                               ignore_missing=True)
    members = member_refs.rel(ignore_missing=True)
    archived = ma.BoolField(required=False, default=False)

    # link to info page
    @property
    def link(self):
        return "/projects/{}".format(self.mongo_id)

    @property
    def render(self):
        return '<a href="{}">{}</a>'.format(self.link, self.name)

    # relationships
    @property
    def servers(self):
        return Servers.query.filter(Servers.project_ref == self.to_ref()).all()

    # indexes
    project_name_index = Index().ascending('name').unique()

    # magic methods
    def __repr__(self):
        return "<Project {}>".format(self.name)

    def __str__(self):
        return str(self.name)
コード例 #11
0
class Manufacturers(ma.Document):

    name = ma.StringField()
    logo = ma.StringField(required=False, allow_none=True, ignore_missing=True)

    def __str__(self):
        return "{}".format(self.name)

    # indexes
    name_index = Index().ascending('name').unique()
コード例 #12
0
    class User(Document):

        name_index = Index().ascending('name').unique()

        name = StringField()
        email = StringField()

        address = DocumentField(Address)

        def __str__(self):
            return '%s (%s)' % (self.name, self.email)
コード例 #13
0
class ServerMemory(ma.Document):

    # parameters
    module_ref = ma.RefField('Memory')
    module = module_ref.rel()
    bank = ma.StringField()
    slot = ma.StringField()
    current_speed = ma.IntField()

    # indexes
    module_index = Index().ascending('module_ref').unique()
コード例 #14
0
class User(db.Document):
    config_collection_name = 'users'

    username = db.StringField(required=True)
    password = db.StringField(required=True)
    token = db.StringField(required=False)
    displayName = db.DocumentField(UserFullName)
    email = db.StringField(required=True)
    email_index = Index().ascending('email').unique()
    adminRights = db.BoolField(required=True)
    paymentInfo = db.DocumentField(PaymentInfo)
    address = db.DocumentField(Address)
コード例 #15
0
class SwitchModels(ma.Document):

    make_ref = ma.RefField('Manufacturers')
    make = make_ref.rel()
    name = ma.StringField()

    # indexes
    model_index = Index().ascending('make').ascending('name').unique()

    # magic_methods
    def __str__(self):
        return "{}".format(self.name)
コード例 #16
0
class RoomTypes(ma.Document):

    # parameters
    type = ma.StringField()

    # magic methods
    def __str__(self):
        return str(self.type)

    def __repr__(self):
        return "<RoomType '{}'>".format(self.type)

    # indexes
    type_index = Index().ascending('type').unique()
コード例 #17
0
class ServerModels(ma.Document):

    make_ref = ma.RefField('Manufacturers')
    make = make_ref.rel()
    name = ma.StringField()
    height = ma.IntField(min_value=1)
    drive_slots = ma.IntField(required=False, allow_none=True)
    modular = ma.BoolField(default=False)

    def __str__(self):
        return "{}".format(self.name)

    # indexes
    make_model_index = Index().ascending('make_ref') \
        .ascending('name').unique()
コード例 #18
0
class DriveModels(ma.Document):

    # parameters
    make_ref = ma.RefField(Manufacturers)
    make = make_ref.rel()
    type_ref = ma.RefField('DriveTypes')
    type = type_ref.rel()
    model = ma.StringField()

    # indexes
    model_index = Index().ascending('model').unique()

    # magic methods
    def __repr__(self):
        return "<DriveModel {} {}>".format(self.make, self.model)

    def __str__(self):
        return "{} {}".format(self.make, self.model)
コード例 #19
0
class FrequencyUnits(ma.Document):

    # parameters
    system_ref = ma.RefField('UnitsSystems',
                             required=False,
                             allow_none=True,
                             ignore_missing=True)
    system = system_ref.rel(allow_none=True)
    name = ma.StringField()
    abbreviation = ma.StringField(required=False,
                                  allow_none=True,
                                  ignore_missing=True)

    # indexes
    unit_index = Index().ascending('name').unique()

    # magic methods
    def __str__(self):
        return '{}'.format(self.abbreviation or self.name)
コード例 #20
0
class ProjectStatusTypes(ma.Document):
    def validate_color(color):
        match_string = re.compile(r'(?i)^(?:[0-9a-fA-F]{3}){1,2}$')
        return bool(match_string.search(color))

    status = ma.StringField()
    background_color = ma.StringField(validator=validate_color,
                                      required=False,
                                      ignore_missing=True,
                                      allow_none=True)
    text_color = ma.StringField(validator=validate_color,
                                required=False,
                                ignore_missing=True,
                                allow_none=True)

    @property
    def style(self):
        if not hasattr(self, 'background_color'):
            print "no background color for {}".format(self.status)
            if not hasattr(self, 'text_color'):
                print "no text color for {}".format(self.status)
                raise Exception('No colors!')

        style_string = ' style="'
        if hasattr(self, 'background_color'):
            style_string += 'background-color:{};'\
                .format(self.background_color)
        if hasattr(self, 'text_color'):
            style_string += 'color:{};'.format(self.text_color)

        return style_string

    def __repr__(self):
        return "<ProjectStatusTypes {}>".format(self.status)

    def __str__(self):
        return str(self.status)

    # indexes
    status_index = Index().ascending('status').unique()
コード例 #21
0
class NetworkInterfaces(ma.Document):
    def _validate_type(type_):
        if type_ not in ('oob', 'ib'):
            raise BadValueException('Wrong interface type.')

    def _validate_mac(value):
        if value != value.replace(':', '').lower():
            raise BadValueException('MAC Address must be in all lower case,'
                                    'and with no special characters')

    # parameters
    serial_number = ma.StringField(required=False, allow_none=True)
    model_ref = ma.RefField('NetworkInterfaceModels',
                            required=False,
                            allow_none=True,
                            ignore_missing=True)
    model = model_ref.rel(allow_none=True)
    mac = ma.StringField(validator=_validate_mac)
    ip = ma.StringField(required=False, allow_none=True, ignore_missing=True)
    name = ma.StringField()
    slot_type = ma.StringField(required=False,
                               allow_none=True,
                               ignore_missing=True)
    slot = ma.IntField()
    port = ma.IntField(required=False, allow_none=True, ignore_missing=True)
    type = ma.StringField(validator=_validate_type)

    @property
    def formatted_mac(self):
        return ":".join(s.encode('hex')
                        for s in self.mac.decode('hex')).upper()

    # indexes
    serial_number_index = SparseIndex().ascending('serial_number').unique()
    mac_index = Index().ascending('mac').unique()

    # magic methods
    def __str__(self):
        return "<NetworkInterfaces {}>".format(self.formatted_mac)
コード例 #22
0
ファイル: FeedsOnAchi.py プロジェクト: mcpoet/easyRSSCrawler
class Newsfeed(Document):
    guid = StringField(_id=True)
    title = StringField()
    description = StringField()
    rssid = StringField(max_length=10, min_length=0,required=False)
    link = StringField()
    # piclink = StringField(required = False)
    # source = StringField(required = False)
    # tags = ListField(StringField(), required = False)
    # date = DateTimeField(required = False)
    # category = ListField(StringField(), required = False)
    # editStatus = IntField(min_value=0, required = False)
    # editorId = IntField(min_value=0, required = False)
    # editorMemo = StringField(required = False)
    # editDate   = DateTimeField(required = False)
    guid_index = Index().ascending('guid').unique()

    def newNewsfeed(jData):
        pass

    def commitEdition(jData):
        pass
コード例 #23
0
class ByteUnits(ma.Document):

    mapping = {
        'kilo': pow(1024, 1),
        'mega': pow(1024, 2),
        'giga': pow(1024, 3),
        'tera': pow(1024, 4),
        'peta': pow(1024, 5),
        'exa': pow(1024, 5),
        'zeta': pow(1024, 6)
    }

    #def _validate_unit(value):
    #    # match prefixes, or first letter of prefix
    #    match = re.match(r'(?is)'
    #                     r'(?:{})|'
    #                     r'(?:[{}](?=b))'
    #                     .format('|'.join(mapping.keys()),
    #                             ''.join([c[0].lower()
    #                                      for c in mapping.keys()])),
    #                     value)
    #    if match:
    #        prefix = match.group()
    #        if prefix:
    #            return True
    #    raise BadValueException

    name = ma.StringField()

    @property
    def abbreviation(self):
        return '{}B'.format(self.name[0].upper())

    # indexes
    unit_index = Index().ascending('name').unique()

    # magic methods
    def __str__(self):
        return '{}'.format(self.abbreviation)
コード例 #24
0
class BaseToken(BaseModel):
    token = StringField(required=True)
    used = BoolField(default=False)
    user_uid = ObjectIdField(required=True)

    i_token = Index().ascending('token').unique()
    i_user_uid = Index().ascending('user_uid')

    def __eq__(self, target):
        return target == self.token

    async def sanitize_data(self, context):
        author = context.get('author')
        data = context.get('data')

        if author:
            if author.role == 'admin':
                return data
            else:
                return []
        else:
            return []

    async def serialize(self, context):
        data = {}
        data['token'] = self.token
        data['user_uid'] = str(self.user_uid)
        data['used'] = self.used
        return data

    async def method_autorized(self, context):
        author = context.get('author')

        if author.role == 'admin':
            return True
        else:
            return False

    async def validate_and_save(self, context):
        data = context.get('data')
        db_session = context.get('db_session')
        save = context.get('save', True)

        is_new = await self.is_new()

        # USED
        used = data.get('used')
        if used is not None:
            self.used = used

        # TOKEN
        token = data.get('token')
        if token:
            self.token = token
        else:
            self.token = generate_token(20)

        # USER UID
        user_uid = data.get('user_uid')
        if user_uid:
            self.user_uid = user_uid
        else:
            if is_new:
                raise exceptions.InvalidRequestException('Missing user_uid')

        if save:
            db_session.save(self, safe=True)

    def use(self, context):
        target = context.get('target')
        user = context.get('user')
        db_session = context.get('db_session')

        if self.used:
            raise exceptions.TokenAlreadyUsedException(self.token)

        if target == self:
            if self.is_expire():
                raise exceptions.TokenExpiredException()

            if self.is_belonging_to_user(user):
                self.used = True

                db_session.save(self, safe=True)

                return True
            else:
                raise exceptions.TokenViolationException(
                    "{user} has not the right to the use the {token})".format(
                        user=user, token=self.token))
        else:
            raise exceptions.TokenInvalidException(
                "{token} != {user_token}".format(token=self.token,
                                                 user_token=target))

    def is_belonging_to_user(self, user):
        return True

    def is_expire(self):
        return False
コード例 #25
0
class TUnique(Document):
    i = IntField()
    main_index = Index().ascending('i').unique()
コード例 #26
0
 class Place(Document):
     config_collection_name = 'places'
     loc = GeoField()
     val = IntField()
     index = Index().geo_haystack('loc', bucket_size=100).descending('val')
コード例 #27
0
 class Place(Document):
     config_collection_name = 'places4'
     loc = GeoField()
     val = IntField()
     index = Index().geo2d('loc', min=-100, max=100)
コード例 #28
0
ファイル: test_index.py プロジェクト: yinpeng/MongoAlchemy
 class TestDoc2(TestDoc):
     index_1 = Index().ascending('noexists')
コード例 #29
0
ファイル: models.py プロジェクト: jianfang/cloudstore
class User(db.Document):
    # fields
    id = db.IntField()
    email = db.StringField(max_length=64)
    username = db.StringField()
    password_hash = db.StringField()
    member_since = db.CreatedField()
    confirmed = db.BoolField()

    # optional fields
    avatar = db.StringField(required=False)
    phone = db.StringField(required=False)
    followed = db.ListField(db.SRefField(Idol), default_empty=True)
    posts = db.ListField(db.SRefField(Post), default_empty=True)
    comments = db.ListField(db.SRefField(Comment), default_empty=True)

    # index
    #email_index = Index().descending('email').unique()
    username_index = Index().descending('username').unique()

    @staticmethod
    def generate_fake(count=100):
        from random import seed
        import forgery_py

        seed()
        for i in range(count):
            u = User(
                id=0,
                email=forgery_py.internet.email_address(),
                username=forgery_py.internet.user_name(True),
                password_hash=generate_password_hash(
                    forgery_py.lorem_ipsum.word()),
                confirmed=False
                # password=forgery_py.lorem_ipsum.word()
                # location=forgery_py.address.city(),
                # about_me=forgery_py.lorem_ipsum.sentence(),
            )
            u.save()

    @staticmethod
    def validate_email(email):
        if User.query.filter_by(email=email).first():
            raise ValidationError('Email already registered.')

    @staticmethod
    def validate_username(username):
        if User.query.filter_by(username=username).first():
            raise ValidationError('Username already in use.',
                                  'USER_ALREADY_EXISTS')

    @staticmethod
    def add_user(email, username, password):
        id = 0
        user = User(id=id,
                    email=email,
                    username=username,
                    password_hash=generate_password_hash(password),
                    confirmed=False)
        user.save()
        return user

    @staticmethod
    def get_user(uid):
        user = User.query.filter(User.mongo_id == uid).first()
        return user

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def generate_auth_token(self, expires_in=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expires_in=expires_in)
        return s.dumps({'username': self.username}).decode('utf-8')

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return None
        return User.query.filter(User.username == data['username']).first()

    def to_json(self):
        json_user = {
            'id': str(self.mongo_id),
            'url': url_for('api.get_user',
                           id=str(self.mongo_id),
                           _external=True),
            'username': self.username,
            'avatar': self.avatar,
            'followed': [str(f) for f in self.followed]
        }
        return json_user

    def to_json_simple(self):
        json_user = {
            'id': str(self.mongo_id),
            'name': self.username,
            'avatar': self.avatar,
        }
        return json_user
コード例 #30
0
class Primes(db.Document):
    max_n = db.IntField()
    values = db.ListField(db.IntField())
    max_n_index = Index().ascending('max_n').unique()