Пример #1
0
    def put(self, meta_type):
        def _get_new_version(service):
            meta = service.get_active()
            if meta:
                return meta['version'] + 1

            raise StatusCodeException('Item metadata not found', 404)

        try:
            if meta_type == 'item':
                service = self.item_meta_service
                new_metadata = request.get_json()
                new_metadata = ItemMetadata(new_metadata,
                                            _get_new_version(service), True)
            elif meta_type == 'user':
                service = self.user_meta_service
                new_metadata = request.get_json()
                new_metadata = UserMetadata(new_metadata,
                                            _get_new_version(service), True)
            else:
                raise StatusCodeException('Invalid type', 400)

            service.disable_all()
            service.insert(new_metadata.to_database())
            return make_response(new_metadata.to_json())

        except StatusCodeException as ex:
            return ex.to_response()
        except Exception as ex:
            return StatusCodeException(ex.message, 500).to_response()
Пример #2
0
    def __init__(self, metadata, version=1, active=False):
        if not metadata:
            raise StatusCodeException('Item metadata not found', 404)

        self.meta = metadata
        self.type = self.meta['type']
        self.attributes = self.meta['attributes']
        self.active = self.meta['active'] if 'active' in self.meta else active
        self.created_at = self.meta[
            'created_at'] if 'created_at' in self.meta else datetime.now()
        self.version = self.meta[
            'version'] if 'version' in self.meta else version

        if self.type != 'item':
            raise StatusCodeException('Invalid type', 400)

        if self.attributes:
            for attribute in self.attributes:
                if 'name' not in attribute:
                    raise StatusCodeException(
                        'Missing name attribute at item metadata', 400)
                elif 'type' not in attribute:
                    raise StatusCodeException(
                        'Missing type for "%s" at item metadata' %
                        attribute['name'], 400)
        else:
            raise StatusCodeException('Missing attributes for item metadata',
                                      400)
Пример #3
0
 def validate(self):
     for attr in self.meta.attributes:
         if attr['name'] not in self.user:
             if 'nullable' not in attr or not attr['nullable']:
                     raise StatusCodeException('Missing %s attribute' % attr['name'], 400)
         elif get_synonymous(type(self.user[attr['name']]).__name__) != attr['type']:
             raise StatusCodeException('%s attribute has wrong type' % attr['name'], 400)
     return True
Пример #4
0
 def delete(self, user_id):
     try:
         if self.service.get_by_id(user_id):
             self.service.remove(user_id)
             return make_response()
         else:
             raise StatusCodeException('User not found', 404)
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #5
0
 def get(self, item_id):
     try:
         item = self.item_service.get_by_id(item_id)
         if item:
             return make_response(ItemModel(item).to_json())
         else:
             raise StatusCodeException('Item not found', 404)
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #6
0
 def put(self, user_id):
     try:
         user = UserModel(request.get_json())
         if user.validate():
             user = UserModel(self.service.update(user_id, user.to_database()))
             return make_response(user.to_json())
         else:
             raise StatusCodeException('User not found', 404)
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #7
0
 def post(self):
     try:
         email = request.data.get('email', None)
         password = request.data.get('password', None)
         if email and password:
             token = auth.generate_token(email, password)
             return make_response({'token': token})
         else:
             raise StatusCodeException('Invalid parameters', 400)
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #8
0
 def post(self):
     try:
         user = UserModel(request.get_json())
         if user.validate():
             user_id = self.service.insert(user.to_database())
             user.set_id(user_id) # XXX - Generate user recommendations
             return make_response(user.to_json())
         else:
             raise StatusCodeException('Conflict', 409)
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #9
0
 def post(self):
     try:
         item = ItemModel(request.get_json())
         if item.validate():
             item_id = self.item_service.insert(item.to_database())
             item.set_id(item_id)
             ContentWorker().train_item(item_id)
             return make_response(item.to_json())
         else:
             raise StatusCodeException('Conflict', 409)
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #10
0
    def recommend(self, item_id, start=0, end=10):
        """
        Couldn't be simpler! Just retrieves the similar items and their 'score' from redis.

        :param item_id: int
        :param number_of_recommendations: number of similar items to return
        :return: A list of lists like: [["19", 0.2203], ["494", 0.1693], ...]. The first item in each sub-list is
        the item ID and the second is the similarity score. Sorted by similarity score, descending.
        """
        item = self.item_service.get_by_id(item_id)
        if item:
            if 'similar' in item:
                similar_items = item['similar'][start:end]
                similar_ids = [it['_id'] for it in item['similar'][start:end]]
                recommendations = self.item_service.get_info(similar_ids)
                json_recs = []
                for rec in recommendations:
                    for similar_item in similar_items:
                        if similar_item['_id'] == rec['_id']:
                            json_recs.append(
                                ItemModel(rec).to_rec_json(
                                    similar_item['similarity']))
                json_recs = sorted(
                    json_recs,
                    cmp=lambda x, y: cmp(x['similarity'], y['similarity']),
                    reverse=True)  #Resort by similarity level
                return json_recs
            return {}
        else:
            raise StatusCodeException('Item not found', 404)
Пример #11
0
 def get(self, item_id, start, end):
     try:
         return make_response(
             self.recommender_service.recommend(item_id, start, end))
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #12
0
 def get(self, item_id):
     try:
         ContentWorker().train_item(item_id)
         return make_response(
         )  # XXX - Separar content worker do prepare pra validar
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #13
0
 def get(self, item_id, number_of_recommendations=10):
     try:
         return make_response(
             self.recommender_service.recommend(
                 item_id, end=number_of_recommendations))
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #14
0
 def get(self, user_id):
     try:
         user = self.service.get_by_id(user_id)
         user = UserModel(user)
         return make_response(user.to_json())
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #15
0
 def get(self):
     try:
         ContentWorker().train()
         CollaborativeWorker().train()
         return make_response()
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         info(traceback.print_exc())
         return StatusCodeException(ex.message, 500).to_response()
Пример #16
0
 def decorated_function(*args, **kwargs):
     try:
         # XXX - Reenable token when finish
         #token = request.headers.get('token', None)
         #if not token or not self.authenticate(token):
         #    raise StatusCodeException('Not authorized', 403)
         return function(*args, **kwargs)
     except StatusCodeException as ex:
         return ex.to_response()
     except Exception as ex:
         return StatusCodeException(ex.message, 500).to_response()
Пример #17
0
    def get(self, meta_type):
        try:
            if meta_type == 'item':
                json_metadata = [
                    ItemMetadata(meta).to_json()
                    for meta in self.item_meta_service.get_all()
                ]
            elif meta_type == 'user':
                json_metadata = [
                    UserMetadata(meta).to_json()
                    for meta in self.user_meta_service.get_all()
                ]
            else:
                raise StatusCodeException('Invalid type', 400)

            return make_response(json_metadata)
        except StatusCodeException as ex:
            return ex.to_response()
        except Exception as ex:
            return StatusCodeException(ex.message, 500).to_response()
Пример #18
0
 def generate_token(self,
                    email,
                    password,
                    expiration=1296000):  # 15 days token
     user_id = self.service.verify(email, password)
     if user_id:
         serializer = Serializer(self.secret_key, expires_in=expiration)
         token = serializer.dumps({'email': email, 'password': password})
         self.service.update_token(user_id, token)
         return token
     else:
         raise StatusCodeException('User not found', 404)
Пример #19
0
    def validate(self):
        """
        Validates existent item attributes based on current
        item metadata.

        It uses item metadata definitions to validate item
        dynamic attributes and values.

        Returns:
            ``True`` if all item attributes match with metadata. Otherwise,
            throw an Exception to eatch type of validation.
        """
        for attr in self.meta.attributes:
            if attr['name'] not in self.item:
                if 'nullable' not in attr or not attr['nullable']:
                    raise StatusCodeException(
                        'Missing %s attribute' % attr['name'], 400)
            elif get_synonymous(type(
                    self.item[attr['name']]).__name__) != attr['type']:
                raise StatusCodeException(
                    '%s attribute has wrong type' % attr['name'], 400)
        return True
Пример #20
0
    def post(self, meta_type):
        try:
            if meta_type == 'item':
                service = self.item_meta_service
                new_metadata = ItemMetadata(request.get_json(),
                                            version=1,
                                            active=True)
            elif meta_type == 'user':
                service = self.user_meta_service
                new_metadata = UserMetadata(request.get_json(),
                                            version=1,
                                            active=True)
            else:
                raise StatusCodeException('Invalid type', 400)

            if not service.get_active():
                service.insert(new_metadata.to_database())
                return make_response(new_metadata.to_json())
            else:
                raise StatusCodeException('Conflict', 409)
        except StatusCodeException as ex:
            return ex.to_response()
        except Exception as ex:
            return StatusCodeException(ex.message, 500).to_response()
Пример #21
0
        def _get_new_version(service):
            meta = service.get_active()
            if meta:
                return meta['version'] + 1

            raise StatusCodeException('Item metadata not found', 404)