Beispiel #1
0
    def post(self):
        """
        Route : POST /
        Description : Creates a collection in the database.
        Returns status
        """

        if not self.app.config['ROOT_POST']:
            abort(405)

        if request.mimetype != 'application/json':
            return send_error(415, "JSON_NEEDED",
                              "Accepted media type : application/json")
        data = request.data
        if isinstance(data, str) or isinstance(data, unicode):
            try:
                data = json.loads(data)
            except JSONDecodeError:
                return send_error(400, "BAD_JSON_FORMAT")
        domain, content = data.popitem()
        if domain in self.app.DOMAINS:
            return send_error(400, message="ALREADY_EXISTS")
        else:
            self.app.DOMAINS[domain] = content
        return send_response(status=201)
Beispiel #2
0
    def get(self):
        """
        Route : GET /
        Returns the list of collections
        """

        if not self.app.config['ROOT_GET']:
            abort(405)

        response = {
            'title': self.app.config['ROOT_TITLE'],
            'description': self.app.config['ROOT_DESCRIPTION'],
            'links': []
        }
        base_url = request.base_url
        response['links'].append(
            get_self_link(title="root",
                          base_url=base_url,
                          description='You are here.',
                          methods=["GET", "POST"]))
        for collection in self.app.DOMAINS:
            response['links'].append(
                get_collection_link(self.app.DOMAINS,
                                    collection,
                                    base_url=base_url))
        return send_response(response)
Beispiel #3
0
    def delete(self, collection):
        """
        Route : DELETE /<collection>/
        Description : Deletes every document in the given collection.
        Returns status
        """

        if not self.app.config['COLLECTION_DELETE']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        self.mongo.db[collection].drop()
        return send_response('')
Beispiel #4
0
    def delete(self, collection):
        """
        Route : DELETE /<collection>/
        Description : Deletes every document in the given collection.
        Returns status
        """

        if not self.app.config['COLLECTION_DELETE']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        self.mongo.db[collection].drop()
        return send_response('')
Beispiel #5
0
    def delete(self, collection, id):
        """
        Route : DELETE /<collection>/<id>
        Description : Deletes the document from the collection.
        Returns the status.
        """

        if not self.app.config['ITEM_DELETE']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        document = self.mongo.db[collection].find_one_or_404({"_id": id})
        self.mongo.db[collection].remove(document)
        return send_response(status=200)
Beispiel #6
0
    def get(self, collection, id):
        """
        Route : GET /<collection>/<id>
        Description : Gets the chosen document.
        Returns the document.
        """

        if not self.app.config['ITEM_GET']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        document = self.mongo.db[collection].find_one_or_404({"_id": id})
        document['etag'] = get_etag(document)
        return send_response(document, etag=document['etag'])
Beispiel #7
0
    def delete(self, collection, id):
        """
        Route : DELETE /<collection>/<id>
        Description : Deletes the document from the collection.
        Returns the status.
        """

        if not self.app.config['ITEM_DELETE']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        document = self.mongo.db[collection].find_one_or_404({"_id": id})
        self.mongo.db[collection].remove(document)
        return send_response(status=200)
Beispiel #8
0
    def get(self, collection, id):
        """
        Route : GET /<collection>/<id>
        Description : Gets the chosen document.
        Returns the document.
        """

        if not self.app.config['ITEM_GET']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        document = self.mongo.db[collection].find_one_or_404({"_id" : id})
        document['etag'] = get_etag(document)
        return send_response(document, etag=document['etag'])
Beispiel #9
0
    def post(self, collection):
        """
        Route : POST /<collection>/
        Description : Creates a list of documents in the database.
        Returns status and _id for each document.
        """

        if not self.app.config['COLLECTION_POST']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        if request.mimetype != 'application/json':
            return send_error(415, "JSON_NEEDED",
                              "Accepted media type : application/json")
        data = request.data
        if not data:
            return send_error(400, "EMPTY_DATA")
        if isinstance(data, str) or isinstance(data, unicode):
            try:
                data = json.loads(data)
            except JSONDecodeError:
                return send_error(400, "BAD_JSON_FORMAT")
        if isinstance(data, dict):
            status = self.validate(data, collection)
            if status['created']:
                base_url = request.base_url
                response = {'title': "Document created", 'links': []}
                response['links'].append(
                    get_self_link(title=self.app.DOMAINS[collection]['title'],
                                  base_url=base_url,
                                  description='You are here.',
                                  methods=["GET", "POST", "DELETE"]))
                response['links'].append(
                    get_document_link(status['document'], base_url))
                return send_response(response, 201,
                                     get_etag(status['document']))
            else:
                return send_error(400, "VALIDATION_ERROR", status['issues'])
        return send_error(400, "BAD_DATA_FORMAT")
Beispiel #10
0
    def get(self, collection):
        """
        Route : GET /<collection>/
        Description : Gets the list of documents in the given collection
        filtered with the given filters
        Returns a list of documents with etag.
        """

        if not self.app.config['COLLECTION_GET']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        args = request.values.to_dict()
        if args:
            args, opts = format_args(args)
            cursor = self.mongo.db[collection].find(args, **opts)
        else:
            cursor = self.mongo.db[collection].find(limit=20)
        base_url = request.base_url

        #: Building response
        response = {'links': [], 'title': '', 'description': ''}
        if 'title' in self.app.DOMAINS[collection]:
            response['title'] = self.app.DOMAINS[collection]['title']
        if 'description' in self.app.DOMAINS[collection]:
            response['description'] = self.app.DOMAINS[collection][
                'description']

        response['links'].append(
            get_self_link(title=response['title'],
                          base_url=base_url,
                          description='You are here.',
                          methods=["GET", "POST", "DELETE"]))
        response['links'].append(get_parent_link(base_url))
        for document in cursor:
            response['links'].append(get_document_link(document, base_url))
        return send_response(response)
Beispiel #11
0
    def post(self, collection):
        """
        Route : POST /<collection>/
        Description : Creates a list of documents in the database.
        Returns status and _id for each document.
        """

        if not self.app.config['COLLECTION_POST']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        if request.mimetype != 'application/json':
            return send_error(415, "JSON_NEEDED", "Accepted media type : application/json")
        data = request.data
        if not data:
            return send_error(400, "EMPTY_DATA")
        if isinstance(data, str) or isinstance(data, unicode):
            try:
                data = json.loads(data)
            except JSONDecodeError:
                return send_error(400, "BAD_JSON_FORMAT")
        if isinstance(data, dict):
            status = self.validate(data, collection)
            if status['created']:
                base_url = request.base_url
                response = {'title': "Document created", 'links': []}
                response['links'].append(get_self_link(
                    title=self.app.DOMAINS[collection]['title'],
                    base_url=base_url,
                    description='You are here.',
                    methods=["GET", "POST", "DELETE"]
                ))
                response['links'].append(get_document_link(status['document'], base_url))
                return send_response(response, 201, get_etag(status['document']))
            else:
                return send_error(400, "VALIDATION_ERROR", status['issues'])
        return send_error(400, "BAD_DATA_FORMAT")
Beispiel #12
0
    def get(self, collection):
        """
        Route : GET /<collection>/
        Description : Gets the list of documents in the given collection
        filtered with the given filters
        Returns a list of documents with etag.
        """

        if not self.app.config['COLLECTION_GET']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        args = request.values.to_dict()
        if args:
            args, opts = format_args(args)
            cursor = self.mongo.db[collection].find(args, **opts)
        else:
            cursor = self.mongo.db[collection].find(limit=20)
        base_url = request.base_url

        #: Building response
        response = {'links' : [], 'title' :'', 'description' : ''}
        if 'title' in self.app.DOMAINS[collection]:
            response['title'] = self.app.DOMAINS[collection]['title']
        if 'description' in self.app.DOMAINS[collection]:
            response['description'] = self.app.DOMAINS[collection]['description']

        response['links'].append(get_self_link(
            title=response['title'],
            base_url=base_url,
            description='You are here.',
            methods=["GET", "POST", "DELETE"]
        ))
        response['links'].append(get_parent_link(base_url))
        for document in cursor:
            response['links'].append(get_document_link(document, base_url))
        return send_response(response)
Beispiel #13
0
    def put(self, collection, id):
        """
        Route : PUT /<collection>/<id>
        Description : Updates the document.
        Returns the status.
        """

        if not self.app.config['ITEM_PUT']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        document = self.mongo.db[collection].find_one_or_404({"_id": id})
        date_utc = datetime.utcnow()
        if request.mimetype != 'application/json':
            return send_error(415, "JSON_NEEDED",
                              "Accepted media type : application/json")
        data = request.data
        if isinstance(data, str) or isinstance(data, unicode):
            try:
                data = json.loads(data)
            except JSONDecodeError:
                return send_error(400, "BAD_JSON_FORMAT")
        for key in data:
            document[key] = data[key]
        copy = {}
        for key in document:
            if key == "created": continue
            if key == "updated": continue
            if key == "_id": continue
            copy[key] = document[key]
        v = Validator()
        if v.validate(copy, self.app.DOMAINS[collection]['schema']):
            document['updated'] = date_utc
            self.mongo.db[collection].save(document)
            return send_response(status=200)
        return send_error(400, "VALIDATION_ERROR", v.error)
Beispiel #14
0
    def post(self):
        """
        Route : POST /
        Description : Creates a collection in the database.
        Returns status
        """

        if not self.app.config['ROOT_POST']:
            abort(405)

        if request.mimetype != 'application/json':
            return send_error(415, "JSON_NEEDED", "Accepted media type : application/json")
        data = request.data
        if isinstance(data, str) or isinstance(data, unicode):
            try:
                data = json.loads(data)
            except JSONDecodeError:
                return send_error(400, "BAD_JSON_FORMAT")
        domain, content = data.popitem()
        if domain in self.app.DOMAINS:
            return send_error(400, message="ALREADY_EXISTS")
        else:
            self.app.DOMAINS[domain] = content
        return send_response(status=201)
Beispiel #15
0
    def get(self):
        """
        Route : GET /
        Returns the list of collections
        """

        if not self.app.config['ROOT_GET']:
            abort(405)

        response = {
            'title' : self.app.config['ROOT_TITLE'],
            'description' : self.app.config['ROOT_DESCRIPTION'],
            'links' : []
        }
        base_url = request.base_url
        response['links'].append(get_self_link(
            title="root",
            base_url=base_url,
            description='You are here.',
            methods=["GET", "POST"]
        ))
        for collection in self.app.DOMAINS:
            response['links'].append(get_collection_link(self.app.DOMAINS, collection, base_url=base_url))
        return send_response(response)
Beispiel #16
0
    def put(self, collection, id):
        """
        Route : PUT /<collection>/<id>
        Description : Updates the document.
        Returns the status.
        """

        if not self.app.config['ITEM_PUT']:
            abort(405)

        if collection not in self.app.DOMAINS:
            abort(404)
        document = self.mongo.db[collection].find_one_or_404({"_id" : id})
        date_utc = datetime.utcnow()
        if request.mimetype != 'application/json':
            return send_error(415, "JSON_NEEDED", "Accepted media type : application/json")
        data = request.data
        if isinstance(data, str) or isinstance(data, unicode):
            try:
                data = json.loads(data)
            except JSONDecodeError:
                return send_error(400, "BAD_JSON_FORMAT")
        for key in data:
            document[key] = data[key]
        copy = {}
        for key in document:
            if key == "created": continue
            if key == "updated": continue
            if key == "_id": continue
            copy[key] = document[key]
        v = Validator()
        if v.validate(copy, self.app.DOMAINS[collection]['schema']):
            document['updated'] = date_utc
            self.mongo.db[collection].save(document)
            return send_response(status=200)
        return send_error(400, "VALIDATION_ERROR", v.error)