Пример #1
0
    def test_pack_query_params_one(self):
        self.assertEqual(
            falcon.to_query_str({'limit': 10}),
            '?limit=10')

        self.assertEqual(
            falcon.to_query_str({'things': [1, 2, 3]}),
            '?things=1,2,3')

        self.assertEqual(
            falcon.to_query_str({'things': ['a']}),
            '?things=a')

        self.assertEqual(
            falcon.to_query_str({'things': ['a', 'b']}),
            '?things=a,b')

        expected = ('?things=a&things=b&things=&things=None'
                    '&things=true&things=false&things=0')

        actual = falcon.to_query_str(
            {'things': ['a', 'b', '', None, True, False, 0]},
            comma_delimited_lists=False
        )

        self.assertEqual(actual, expected)
Пример #2
0
    def test_pack_query_params_one(self):
        self.assertEqual(
            falcon.to_query_str({'limit': 10}),
            '?limit=10')

        self.assertEqual(
            falcon.to_query_str({'things': [1, 2, 3]}),
            '?things=1,2,3')

        self.assertEqual(
            falcon.to_query_str({'things': ['a']}),
            '?things=a')

        self.assertEqual(
            falcon.to_query_str({'things': ['a', 'b']}),
            '?things=a,b')

        expected = ('?things=a&things=b&things=&things=None'
                    '&things=true&things=false&things=0')

        actual = falcon.to_query_str(
            {'things': ['a', 'b', '', None, True, False, 0]},
            comma_delimited_lists=False
        )

        self.assertEqual(actual, expected)
Пример #3
0
    def test_pack_query_params_one(self):
        self.assertEqual(falcon.to_query_str({"limit": 10}), "?limit=10")

        self.assertEqual(falcon.to_query_str({"things": [1, 2, 3]}), "?things=1,2,3")

        self.assertEqual(falcon.to_query_str({"things": ["a"]}), "?things=a")

        self.assertEqual(falcon.to_query_str({"things": ["a", "b"]}), "?things=a,b")
Пример #4
0
    def test_pack_query_params_one(self):
        self.assertEqual(falcon.to_query_str({'limit': 10}), '?limit=10')

        self.assertEqual(falcon.to_query_str({'things': [1, 2, 3]}),
                         '?things=1,2,3')

        self.assertEqual(falcon.to_query_str({'things': ['a']}), '?things=a')

        self.assertEqual(falcon.to_query_str({'things': ['a', 'b']}),
                         '?things=a,b')
Пример #5
0
    def _get(self, req, project_id, queue_name):
        client_uuid = wsgi_helpers.get_client_uuid(req)
        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)
        req.get_param_as_bool('echo', store=kwargs)
        req.get_param_as_bool('include_claimed', store=kwargs)

        try:
            self._validate.message_listing(**kwargs)
            results = self._message_controller.list(
                queue_name,
                project=project_id,
                client_uuid=client_uuid,
                **kwargs)

            # Buffer messages
            cursor = next(results)
            messages = list(cursor)

        except validation.ValidationFailed as ex:
            LOG.debug(ex)
            raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))

        except storage_errors.QueueDoesNotExist as ex:
            LOG.debug(ex)
            messages = None

        except Exception as ex:
            LOG.exception(ex)
            description = _(u'Messages could not be listed.')
            raise wsgi_errors.HTTPServiceUnavailable(description)

        if not messages:
            messages = []

        else:
            # Found some messages, so prepare the response
            kwargs['marker'] = next(results)
            base_path = req.path.rsplit('/', 1)[0]
            messages = [wsgi_utils.format_message_v1_1(m, base_path,
                                                       m['claim_id'])
                        for m in messages]

        links = []
        if messages:
            links = [
                {
                    'rel': 'next',
                    'href': req.path + falcon.to_query_str(kwargs)
                }
            ]

        return {
            'messages': messages,
            'links': links
        }
Пример #6
0
    def test_pack_query_params_one(self):
        self.assertEqual(
            falcon.to_query_str({'limit': 10}),
            '?limit=10')

        self.assertEqual(
            falcon.to_query_str({'things': [1, 2, 3]}),
            '?things=1,2,3')

        self.assertEqual(
            falcon.to_query_str({'things': ['a']}),
            '?things=a')

        self.assertEqual(
            falcon.to_query_str({'things': ['a', 'b']}),
            '?things=a,b')
Пример #7
0
    def test_pack_query_params_several(self):
        garbage_in = {
            'limit': 17,
            'echo': True,
            'doit': False,
            'x': 'val',
            'y': 0.2
        }

        query_str = falcon.to_query_str(garbage_in)
        fields = query_str[1:].split('&')

        garbage_out = {}
        for field in fields:
            k, v = field.split('=')
            garbage_out[k] = v

        expected = {
            'echo': 'true',
            'limit': '17',
            'x': 'val',
            'y': '0.2',
            'doit': 'false',
        }

        assert expected == garbage_out
Пример #8
0
    def test_pack_query_params_several(self):
        garbage_in = {
            'limit': 17,
            'echo': True,
            'doit': False,
            'x': 'val',
            'y': 0.2
        }

        query_str = falcon.to_query_str(garbage_in)
        fields = query_str[1:].split('&')

        garbage_out = {}
        for field in fields:
            k, v = field.split('=')
            garbage_out[k] = v

        expected = {
            'echo': 'true',
            'limit': '17',
            'x': 'val',
            'y': '0.2',
            'doit': 'false'}

        self.assertEqual(expected, garbage_out)
Пример #9
0
    def geocode(self, addr):
        url = self.bing_url
        params = {
            'query': addr,
            'key': self.bing_key,
            'userMapView': self.geocoding_bounding_box,
        }
        url += falcon.to_query_str(params)

        data = session.get(url).json()
        if data['statusCode'] != 200:
            return []

        points = []
        for result in data['resourceSets'][0]['resources']:
            if result['address']['countryRegion'] != self.geocoding_country:
                continue
            lat, lon = result['point']['coordinates']
            points.append({
                'address': result['name'],
                'latitude': lat,
                'longitude': lon,
            })

        return points
Пример #10
0
    def _get(self, req, project_id, queue_name):
        client_uuid = wsgi_helpers.get_client_uuid(req)
        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)
        req.get_param_as_bool('echo', store=kwargs)
        req.get_param_as_bool('include_claimed', store=kwargs)

        try:
            self._validate.message_listing(**kwargs)
            results = self._message_controller.list(
                queue_name,
                project=project_id,
                client_uuid=client_uuid,
                **kwargs)

            # Buffer messages
            cursor = next(results)
            messages = list(cursor)

        except validation.ValidationFailed as ex:
            LOG.debug(ex)
            raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))

        except storage_errors.QueueDoesNotExist as ex:
            LOG.debug(ex)
            messages = None

        except Exception as ex:
            LOG.exception(ex)
            description = _(u'Messages could not be listed.')
            raise wsgi_errors.HTTPServiceUnavailable(description)

        if not messages:
            messages = []

        else:
            # Found some messages, so prepare the response
            kwargs['marker'] = next(results)
            base_path = req.path.rsplit('/', 1)[0]
            messages = [wsgi_utils.format_message_v1_1(m, base_path,
                                                       m['claim_id'])
                        for m in messages]

        links = []
        if messages:
            links = [
                {
                    'rel': 'next',
                    'href': req.path + falcon.to_query_str(kwargs)
                }
            ]

        return {
            'messages': messages,
            'links': links
        }
Пример #11
0
    def on_get(self, request, response, project_id):
        """Returns a flavor listing as objects embedded in an object:

        ::

            {
                "flavors": [
                    {"href": "", "capabilities": {}, "pool_group": ""},
                    ...
                ],
                "links": [
                    {"rel": "next", "href": ""},
                    ...
                ]
            }

        :returns: HTTP | 200
        """

        LOG.debug(u'LIST flavors for project_id %s' % project_id)

        store = {}
        request.get_param('marker', store=store)
        request.get_param_as_int('limit', store=store)
        detailed = request.get_param_as_bool('detailed')

        cursor = self._ctrl.list(project=project_id, **store)
        flavors = list(next(cursor))

        results = {'links': []}

        if flavors:
            store['marker'] = next(cursor)

            for entry in flavors:
                entry['href'] = request.path + '/' + entry['name']
                pool_group = entry['pool_group']
                # NOTE(wanghao): remove this in Newton.
                entry['pool'] = entry['pool_group']
                if detailed:
                    caps = self._pools_ctrl.capabilities(group=pool_group)
                    entry['capabilities'] = [
                        str(cap).split('.')[-1] for cap in caps
                    ]

        if detailed is not None:
            store['detailed'] = detailed

        if flavors:
            results['links'] = [{
                'rel':
                'next',
                'href':
                request.path + falcon.to_query_str(store)
            }]

        results['flavors'] = flavors

        response.body = transport_utils.to_json(results)
        response.status = falcon.HTTP_200
Пример #12
0
    def _on_get_with_kfilter(self, req, resp, project_id, kfilter={}):
        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)
        req.get_param_as_bool('detailed', store=kwargs)
        req.get_param('name', store=kwargs)

        queues, marker = self._queue_list(project_id,
                                          req.path, kfilter, **kwargs)

        links = []
        kwargs['marker'] = marker
        if queues:
            links = [
                {
                    'rel': 'next',
                    'href': req.path + falcon.to_query_str(kwargs)
                }
            ]

        response_body = {
            'queues': queues,
            'links': links
        }

        resp.body = utils.to_json(response_body)
Пример #13
0
    def _on_get_with_kfilter(self, req, resp, project_id, kfilter={}):
        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)
        req.get_param_as_bool('detailed', store=kwargs)
        req.get_param('name', store=kwargs)

        topics, marker = self._topic_list(project_id,
                                          req.path, kfilter, **kwargs)

        links = []
        kwargs['marker'] = marker
        if topics:
            links = [
                {
                    'rel': 'next',
                    'href': req.path + falcon.to_query_str(kwargs)
                }
            ]

        response_body = {
            'topics': topics,
            'links': links
        }

        resp.body = utils.to_json(response_body)
Пример #14
0
    def _get(self, req, project_id, queue_name):
        uuid = req.get_header('Client-ID', required=True)

        # TODO(kgriffs): Optimize
        kwargs = utils.purge({
            'marker': req.get_param('marker'),
            'limit': req.get_param_as_int('limit'),
            'echo': req.get_param_as_bool('echo'),
            'include_claimed': req.get_param_as_bool('include_claimed'),
        })

        try:
            results = self.message_controller.list(
                queue_name,
                project=project_id,
                client_uuid=uuid,
                **kwargs)

            # Buffer messages
            cursor = next(results)
            messages = list(cursor)

        except storage_exceptions.DoesNotExist:
            raise falcon.HTTPNotFound()

        except storage_exceptions.MalformedMarker:
            title = _('Invalid query string parameter')
            description = _('The value for the query string '
                            'parameter "marker" could not be '
                            'parsed. We recommend using the '
                            '"next" URI from a previous '
                            'request directly, rather than '
                            'constructing the URI manually. ')

            raise falcon.HTTPBadRequest(title, description)

        except Exception as ex:
            LOG.exception(ex)
            description = _('Messages could not be listed.')
            raise wsgi_exceptions.HTTPServiceUnavailable(description)

        if not messages:
            return None

        # Found some messages, so prepare the response
        kwargs['marker'] = next(results)
        for each_message in messages:
            each_message['href'] = req.path + '/' + each_message['id']
            del each_message['id']

        return {
            'messages': messages,
            'links': [
                {
                    'rel': 'next',
                    'href': req.path + falcon.to_query_str(kwargs)
                }
            ]
        }
Пример #15
0
    def on_get(self, request, response, project_id):
        """Returns a flavor listing as objects embedded in an object:

        ::

            {
                "flavors": [
                    {"href": "", "capabilities": {}, "pool_group": ""},
                    ...
                ],
                "links": [
                    {"rel": "next", "href": ""},
                    ...
                ]
            }

        :returns: HTTP | 200
        """

        LOG.debug(u'LIST flavors for project_id %s' % project_id)

        store = {}
        request.get_param('marker', store=store)
        request.get_param_as_int('limit', store=store)
        detailed = request.get_param_as_bool('detailed')

        cursor = self._ctrl.list(project=project_id, **store)
        flavors = list(next(cursor))

        results = {'links': []}

        if flavors:
            store['marker'] = next(cursor)

            for entry in flavors:
                entry['href'] = request.path + '/' + entry['name']
                pool_group = entry['pool_group']
                # NOTE(wanghao): remove this in Newton.
                entry['pool'] = entry['pool_group']
                if detailed:
                    caps = self._pools_ctrl.capabilities(group=pool_group)
                    entry['capabilities'] = [str(cap).split('.')[-1]
                                             for cap in caps]

        if detailed is not None:
            store['detailed'] = detailed

        if flavors:
            results['links'] = [
                {
                    'rel': 'next',
                    'href': request.path + falcon.to_query_str(store)
                }
            ]

        results['flavors'] = flavors

        response.body = transport_utils.to_json(results)
        response.status = falcon.HTTP_200
Пример #16
0
    def test_pack_query_params_one(self):
        assert falcon.to_query_str({'limit': 10}) == '?limit=10'

        assert falcon.to_query_str({'things': [1, 2, 3]}) == '?things=1,2,3'

        assert falcon.to_query_str({'things': ['a']}) == '?things=a'

        assert falcon.to_query_str({'things': ['a', 'b']}) == '?things=a,b'

        expected = ('?things=a&things=b&things=&things=None'
                    '&things=true&things=false&things=0')

        actual = falcon.to_query_str(
            {'things': ['a', 'b', '', None, True, False, 0]},
            comma_delimited_lists=False)

        assert actual == expected
Пример #17
0
    def test_failed_parse(self):
        self.tracker_manager.prepare_add_topic = MagicMock(return_value=False)

        topic_parse = TopicParse(self.tracker_manager)
        self.api.add_route('/api/parse', topic_parse)

        self.simulate_request('/api/parse', query_string=falcon.to_query_str({'url': 'http://1'})[1:])
        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
        self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])
Пример #18
0
    def test_pack_query_params_one(self):
        assert falcon.to_query_str({'limit': 10}) == '?limit=10'

        assert falcon.to_query_str(
            {'things': [1, 2, 3]}) == '?things=1,2,3'

        assert falcon.to_query_str({'things': ['a']}) == '?things=a'

        assert falcon.to_query_str(
            {'things': ['a', 'b']}) == '?things=a,b'

        expected = ('?things=a&things=b&things=&things=None'
                    '&things=true&things=false&things=0')

        actual = falcon.to_query_str(
            {'things': ['a', 'b', '', None, True, False, 0]},
            comma_delimited_lists=False
        )

        assert actual == expected
Пример #19
0
    def on_get(self, request, response, project_id):
        """Returns a pool listing as objects embedded in an object:

        ::

            {
                "pools": [
                    {"href": "", "weight": 100, "uri": ""},
                    ...
                ],
                "links": [
                    {"href": "", "rel": "next"}
                ]
            }

        :returns: HTTP | 200
        """

        LOG.debug(u'LIST pools')

        store = {}
        request.get_param('marker', store=store)
        request.get_param_as_int('limit', store=store)
        request.get_param_as_bool('detailed', store=store)

        try:
            self._validate.pool_listing(**store)
        except validation.ValidationFailed as ex:
            LOG.debug(ex)
            raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))

        cursor = self._ctrl.list(**store)
        pools = list(next(cursor))

        results = {'links': []}

        if pools:
            store['marker'] = next(cursor)

            for entry in pools:
                entry['href'] = request.path + '/' + entry['name']

            results['links'] = [
                {
                    'rel': 'next',
                    'href': request.path + falcon.to_query_str(store)
                }
            ]

        results['pools'] = pools

        response.content_location = request.relative_uri
        response.body = transport_utils.to_json(results)
        response.status = falcon.HTTP_200
Пример #20
0
    def _get(self, req, project_id, queue_name):
        uuid = req.get_header('Client-ID', required=True)

        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)
        req.get_param_as_bool('echo', store=kwargs)
        req.get_param_as_bool('include_claimed', store=kwargs)

        try:
            validate.message_listing(**kwargs)
            results = self.message_controller.list(
                queue_name,
                project=project_id,
                client_uuid=uuid,
                **kwargs)

            # Buffer messages
            cursor = next(results)
            messages = list(cursor)

        except input_exceptions.ValidationFailed as ex:
            raise wsgi_exceptions.HTTPBadRequestBody(str(ex))

        except storage_exceptions.DoesNotExist:
            raise falcon.HTTPNotFound()

        except Exception as ex:
            LOG.exception(ex)
            description = _(u'Messages could not be listed.')
            raise wsgi_exceptions.HTTPServiceUnavailable(description)

        if not messages:
            return None

        # Found some messages, so prepare the response
        kwargs['marker'] = next(results)
        for each_message in messages:
            each_message['href'] = req.path + '/' + each_message['id']
            del each_message['id']

        return {
            'messages': messages,
            'links': [
                {
                    'rel': 'next',
                    'href': req.path + falcon.to_query_str(kwargs)
                }
            ]
        }
Пример #21
0
    def test_failed_parse(self):
        self.tracker_manager.prepare_add_topic = MagicMock(return_value=False)

        topic_parse = TopicParse(self.tracker_manager)
        self.api.add_route('/api/parse', topic_parse)

        self.simulate_request('/api/parse',
                              query_string=falcon.to_query_str(
                                  {'url': 'http://1'})[1:])
        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
        self.assertTrue(
            'application/json' in self.srmock.headers_dict['Content-Type'])
Пример #22
0
    def _get(self, req, project_id, queue_name):
        client_uuid = wsgi_utils.get_client_uuid(req)
        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)
        req.get_param_as_bool('echo', store=kwargs)
        req.get_param_as_bool('include_claimed', store=kwargs)

        try:
            self._validate.message_listing(**kwargs)
            results = self.message_controller.list(
                queue_name,
                project=project_id,
                client_uuid=client_uuid,
                **kwargs)

            # Buffer messages
            cursor = next(results)
            messages = list(cursor)

        except validation.ValidationFailed as ex:
            raise wsgi_exceptions.HTTPBadRequestAPI(six.text_type(ex))

        except storage_exceptions.DoesNotExist:
            raise falcon.HTTPNotFound()

        except Exception as ex:
            LOG.exception(ex)
            description = _(u'Messages could not be listed.')
            raise wsgi_exceptions.HTTPServiceUnavailable(description)

        if not messages:
            return None

        # Found some messages, so prepare the response
        kwargs['marker'] = next(results)
        for each_message in messages:
            each_message['href'] = req.path + '/' + each_message['id']
            del each_message['id']

        return {
            'messages': messages,
            'links': [
                {
                    'rel': 'next',
                    'href': req.path + falcon.to_query_str(kwargs)
                }
            ]
        }
Пример #23
0
    def on_get(self, request, response, project_id):
        """Returns a flavor listing as objects embedded in an object:

        ::

            {
                "flavors": [
                    {"href": "", "capabilities": {}, "pool": ""},
                    ...
                ],
                "links": [
                    {"rel": "next", "href": ""},
                    ...
                ]
            }

        :returns: HTTP | 200
        """

        LOG.debug(u"LIST flavors for project_id %s" % project_id)

        store = {}
        request.get_param("marker", store=store)
        request.get_param_as_int("limit", store=store)
        detailed = request.get_param_as_bool("detailed")

        cursor = self._ctrl.list(project=project_id, **store)
        flavors = list(next(cursor))

        results = {"links": []}

        if flavors:
            store["marker"] = next(cursor)

            for entry in flavors:
                entry["href"] = request.path + "/" + entry["name"]
                if detailed:
                    caps = self._pools_ctrl.capabilities(group=entry["pool"])
                    entry["capabilities"] = [str(cap).split(".")[-1] for cap in caps]

        if detailed is not None:
            store["detailed"] = detailed

        if flavors:
            results["links"] = [{"rel": "next", "href": request.path + falcon.to_query_str(store)}]

        results["flavors"] = flavors

        response.body = transport_utils.to_json(results)
        response.status = falcon.HTTP_200
Пример #24
0
    def test_pack_query_params_several(self):
        garbage_in = {"limit": 17, "echo": True, "doit": False, "x": "val", "y": 0.2}

        query_str = falcon.to_query_str(garbage_in)
        fields = query_str[1:].split("&")

        garbage_out = {}
        for field in fields:
            k, v = field.split("=")
            garbage_out[k] = v

        expected = {"echo": "true", "limit": "17", "x": "val", "y": "0.2", "doit": "false"}

        self.assertEqual(expected, garbage_out)
Пример #25
0
    def on_get(self, req, resp, project_id):
        LOG.debug(u'Queue collection GET - project: %(project)s',
                  {'project': project_id})

        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)
        req.get_param_as_bool('detailed', store=kwargs)

        try:
            self._validate.queue_listing(**kwargs)
            results = self.queue_controller.list(project=project_id, **kwargs)

        except validation.ValidationFailed as ex:
            LOG.debug(ex)
            raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))

        except Exception as ex:
            LOG.exception(ex)
            description = _(u'Queues could not be listed.')
            raise wsgi_errors.HTTPServiceUnavailable(description)

        # Buffer list of queues
        queues = list(next(results))

        # Check for an empty list
        if len(queues) == 0:
            resp.status = falcon.HTTP_204
            return

        # Got some. Prepare the response.
        kwargs['marker'] = next(results)
        for each_queue in queues:
            each_queue['href'] = req.path + '/' + each_queue['name']

        response_body = {
            'queues': queues,
            'links': [
                {
                    'rel': 'next',
                    'href': req.path + falcon.to_query_str(kwargs)
                }
            ]
        }

        resp.content_location = req.relative_uri
        resp.body = utils.to_json(response_body)
Пример #26
0
 def jsonapi(self, data, original_data):
     """ add jsonapi data to row """
     # xxx: if we exclude / only the id attr, then the _links.self fail, because the id field never gets this far
     q_str = {}
     if self.only:
         q_str["fields"] = list(self.only)
     if self.exclude:
         q_str["exclude"] = list(self.exclude)
     data["_links"] = {
         "self": "/%s/%s" % (self.__class__._endpoint, original_data.oid),
         "rel": "/%s/%s%s"
         % (self.__class__._endpoint, original_data.oid, falcon.to_query_str(q_str)),
     }
     return data
Пример #27
0
    def on_get(self, req, resp, project_id):
        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)
        req.get_param_as_bool('detailed', store=kwargs)

        try:
            self._validate.queue_listing(**kwargs)
            results = self._queue_controller.list(project=project_id, **kwargs)

            # Buffer list of queues
            queues = list(next(results))

        except validation.ValidationFailed as ex:
            LOG.debug(ex)
            raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))

        except Exception as ex:
            LOG.exception(ex)
            description = _(u'Queues could not be listed.')
            raise wsgi_errors.HTTPServiceUnavailable(description)

        # Got some. Prepare the response.
        kwargs['marker'] = next(results) or kwargs.get('marker', '')
        reserved_metadata = _get_reserved_metadata(self._validate).items()
        for each_queue in queues:
            each_queue['href'] = req.path + '/' + each_queue['name']
            if kwargs.get('detailed'):
                for meta, value in reserved_metadata:
                    if not each_queue.get('metadata', {}).get(meta):
                        each_queue['metadata'][meta] = value

        links = []
        if queues:
            links = [
                {
                    'rel': 'next',
                    'href': req.path + falcon.to_query_str(kwargs)
                }
            ]

        response_body = {
            'queues': queues,
            'links': links
        }

        resp.body = utils.to_json(response_body)
Пример #28
0
    def on_get(self, request, response, project_id):
        """Returns a flavor listing as objects embedded in an object:

        ::

            {
                "flavors": [
                    {"href": "", "capabilities": {}, "pool": ""},
                    ...
                ],
                "links": [
                    {"rel": "next", "href": ""},
                    ...
                ]
            }

        :returns: HTTP | 200
        """

        LOG.debug(u'LIST flavors for project_id %s' % project_id)

        store = {}
        request.get_param('marker', store=store)
        request.get_param_as_int('limit', store=store)
        request.get_param_as_bool('detailed', store=store)

        cursor = self._ctrl.list(project=project_id, **store)
        flavors = list(next(cursor))

        results = {'links': []}

        if flavors:
            store['marker'] = next(cursor)

            for entry in flavors:
                entry['href'] = request.path + '/' + entry['name']

            results['links'] = [{
                'rel':
                'next',
                'href':
                request.path + falcon.to_query_str(store)
            }]

        results['flavors'] = flavors

        response.body = transport_utils.to_json(results)
        response.status = falcon.HTTP_200
Пример #29
0
    def on_get(self, request, response, project_id):
        """Returns a pool listing as objects embedded in an object:

        ::

            {
                "pools": [
                    {"href": "", "weight": 100, "uri": ""},
                    ...
                ],
                "links": [
                    {"href": "", "rel": "next"}
                ]
            }

        :returns: HTTP | 200
        """

        LOG.debug(u'LIST pools')

        store = {}
        request.get_param('marker', store=store)
        request.get_param_as_int('limit', store=store)
        request.get_param_as_bool('detailed', store=store)

        cursor = self._ctrl.list(**store)
        pools = list(next(cursor))

        results = {'links': []}

        if pools:
            store['marker'] = next(cursor)

            for entry in pools:
                entry['href'] = request.path + '/' + entry['name']

            results['links'] = [
                {
                    'rel': 'next',
                    'href': request.path + falcon.to_query_str(store)
                }
            ]

        results['pools'] = pools

        response.content_location = request.relative_uri
        response.body = transport_utils.to_json(results)
        response.status = falcon.HTTP_200
Пример #30
0
    def on_get(self, request, response, project_id):
        """Returns a flavor listing as objects embedded in an object:

        ::

            {
                "flavors": [
                    {"href": "", "capabilities": {}, "pool": ""},
                    ...
                ],
                "links": [
                    {"rel": "next", "href": ""},
                    ...
                ]
            }

        :returns: HTTP | 200
        """

        LOG.debug(u'LIST flavors for project_id %s' % project_id)

        store = {}
        request.get_param('marker', store=store)
        request.get_param_as_int('limit', store=store)
        request.get_param_as_bool('detailed', store=store)

        cursor = self._ctrl.list(project=project_id, **store)
        flavors = list(next(cursor))

        results = {'links': []}

        if flavors:
            store['marker'] = next(cursor)

            for entry in flavors:
                entry['href'] = request.path + '/' + entry['name']

            results['links'] = [
                {
                    'rel': 'next',
                    'href': request.path + falcon.to_query_str(store)
                }
            ]

        results['flavors'] = flavors

        response.body = transport_utils.to_json(results)
        response.status = falcon.HTTP_200
Пример #31
0
    def test_success_parse(self):
        topic = {'display_name': '1', 'form': {}}
        self.tracker_manager.prepare_add_topic = MagicMock(return_value=topic)

        topic_parse = TopicParse(self.tracker_manager)
        self.api.add_route('/api/parse', topic_parse)

        body = self.simulate_request('/api/parse', query_string=falcon.to_query_str({'url': 'http://1'})[1:],
                                     decode='utf-8')
        self.assertEqual(self.srmock.status, falcon.HTTP_OK)
        self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])

        result = json.loads(body)

        self.assertIsInstance(result, dict)
        self.assertEqual(result, topic)
Пример #32
0
    def on_get(self, req, resp, project_id, queue_name):
        LOG.debug(
            u'Subscription collection GET - project: %(project)s, '
            u'queue: %(queue)s', {
                'project': project_id,
                'queue': queue_name
            })

        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)

        try:
            self._validate.subscription_listing(**kwargs)
            results = self._subscription_controller.list(queue_name,
                                                         project=project_id,
                                                         **kwargs)
        except validation.ValidationFailed as ex:
            LOG.debug(ex)
            raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))

        except Exception as ex:
            LOG.exception(ex)
            description = _(u'Subscriptions could not be listed.')
            raise wsgi_errors.HTTPServiceUnavailable(description)

        # Buffer list of subscriptions
        subscriptions = list(next(results))

        # Got some. Prepare the response.
        kwargs['marker'] = next(results) or kwargs.get('marker', '')

        response_body = {
            'subscriptions':
            subscriptions,
            'links': [{
                'rel': 'next',
                'href': req.path + falcon.to_query_str(kwargs)
            }]
        }

        resp.body = utils.to_json(response_body)
Пример #33
0
    def on_get(self, request, response):
        project = helpers.get_project(request)
        LOG.debug('LIST queues - project: {0}'.format(project))

        kwargs = {}
        request.get_param('marker', store=kwargs)
        request.get_param_as_int('limit', store=kwargs)
        request.get_param_as_bool('detailed', store=kwargs)

        resp = collections.defaultdict(list)
        limit = kwargs.get('limit', STORAGE_LIMITS.default_queue_paging)

        try:
            validate.queue_listing(limit=limit)
        except validate.ValidationFailed as ex:
            raise wsgi_exceptions.HTTPBadRequestAPI(six.text_type(ex))

        for queue in self._catalogue.list(project):
            queue_name = queue['name']
            if queue_name < kwargs.get('marker', ''):
                continue
            entry = {
                'href': request.path + '/' + queue_name,
                'name': queue_name
            }
            if kwargs.get('detailed', None):
                entry['metadata'] = queue['metadata']
            resp['queues'].append(entry)
            kwargs['marker'] = queue_name
            if len(resp['queues']) == limit:
                break

        if not resp:
            LOG.debug('LIST queues - no queues found')
            response.status = falcon.HTTP_204
            return

        resp['links'].append({
            'rel': 'next',
            'href': request.path + falcon.to_query_str(kwargs)
        })

        response.content_location = request.relative_uri
        response.body = json.dumps(resp, ensure_ascii=False)
Пример #34
0
    def test_success_parse(self):
        topic = {'display_name': '1', 'form': {}}
        self.tracker_manager.prepare_add_topic = MagicMock(return_value=topic)

        topic_parse = TopicParse(self.tracker_manager)
        self.api.add_route('/api/parse', topic_parse)

        body = self.simulate_request('/api/parse',
                                     query_string=falcon.to_query_str(
                                         {'url': 'http://1'})[1:],
                                     decode='utf-8')
        self.assertEqual(self.srmock.status, falcon.HTTP_OK)
        self.assertTrue(
            'application/json' in self.srmock.headers_dict['Content-Type'])

        result = json.loads(body)

        self.assertIsInstance(result, dict)
        self.assertEqual(result, topic)
Пример #35
0
 def test_pack_query_params_none(self):
     assert falcon.to_query_str({}) == ''
Пример #36
0
 def test_pack_query_params_one(self):
     self.assertEquals(falcon.to_query_str({'limit': 10}), '?limit=10')
Пример #37
0
    def _get(self, req, project_id, queue_name):
        client_uuid = wsgi_helpers.get_client_uuid(req)
        kwargs = {}

        # NOTE(kgriffs): This syntax ensures that
        # we don't clobber default values with None.
        req.get_param('marker', store=kwargs)
        req.get_param_as_int('limit', store=kwargs)
        req.get_param_as_bool('echo', store=kwargs)
        req.get_param_as_bool('include_claimed', store=kwargs)
        req.get_param_as_bool('include_delayed', store=kwargs)

        try:
            queue_meta = {}
            try:
                # NOTE(cdyangzhenyu): In order to determine whether the
                # queue has a delay attribute, the metadata of the queue
                # is obtained here. This may have a little performance impact.
                # So maybe a refactor is needed in the future.
                queue_meta = self._queue_controller.get_metadata(
                    queue_name, project_id)
            except storage_errors.DoesNotExist as ex:
                LOG.exception(ex)
            queue_delay = queue_meta.get('_default_message_delay')
            if not queue_delay:
                # NOTE(cdyangzhenyu): If the queue without the metadata
                # attribute _default_message_delay, we don't filter
                # for delay messages.
                kwargs['include_delayed'] = True

            self._validate.message_listing(**kwargs)
            results = self._message_controller.list(queue_name,
                                                    project=project_id,
                                                    client_uuid=client_uuid,
                                                    **kwargs)

            # Buffer messages
            cursor = next(results)
            messages = list(cursor)

        except validation.ValidationFailed as ex:
            LOG.debug(ex)
            raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))

        except storage_errors.QueueDoesNotExist as ex:
            LOG.debug(ex)
            messages = None

        except Exception as ex:
            LOG.exception(ex)
            description = _(u'Messages could not be listed.')
            raise wsgi_errors.HTTPServiceUnavailable(description)

        if not messages:
            messages = []

        else:
            # Found some messages, so prepare the response
            kwargs['marker'] = next(results)
            base_path = req.path.rsplit('/', 1)[0]
            messages = [
                wsgi_utils.format_message_v1_1(m, base_path, m['claim_id'])
                for m in messages
            ]

        links = []
        if messages:
            links = [{
                'rel': 'next',
                'href': req.path + falcon.to_query_str(kwargs)
            }]

        return {'messages': messages, 'links': links}
Пример #38
0
    def on_get(self, request, response, project_id):
        """Returns a flavor listing as objects embedded in an object:

        ::

            {
                "flavors": [
                    {"href": "", "capabilities": {},
                     "pool_list": ""},
                    ...
                ],
                "links": [
                    {"rel": "next", "href": ""},
                    ...
                ]
            }

        :returns: HTTP | 200
        """

        LOG.debug(u'LIST flavors for project_id %s', project_id)
        store = {}
        request.get_param('marker', store=store)
        request.get_param_as_int('limit', store=store)
        detailed = request.get_param_as_bool('detailed')

        try:
            self._validate.flavor_listing(**store)
        except validation.ValidationFailed as ex:
            LOG.debug(ex)
            raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))

        cursor = self._ctrl.list(project=project_id, **store)
        flavors = list(next(cursor))

        results = {'links': []}

        if flavors:
            store['marker'] = next(cursor)

            for entry in flavors:
                entry['href'] = request.path + '/' + entry['name']
                data = {}
                data['name'] = entry['name']
                pool_list = \
                    list(self._pools_ctrl.get_pools_by_flavor(flavor=data))
                pool_name_list = []
                if len(pool_list) > 0:
                    pool_name_list = [x['name'] for x in pool_list]
                    entry['pool_list'] = pool_name_list
                if detailed:
                    caps = self._pools_ctrl.capabilities(flavor=entry)
                    entry['capabilities'] = [
                        str(cap).split('.')[-1] for cap in caps
                    ]

        if detailed is not None:
            store['detailed'] = detailed

        if flavors:
            results['links'] = [{
                'rel':
                'next',
                'href':
                request.path + falcon.to_query_str(store)
            }]

        results['flavors'] = flavors

        response.body = transport_utils.to_json(results)
        response.status = falcon.HTTP_200
Пример #39
0
 def test_pack_query_params_none(self):
     self.assertEqual(falcon.to_query_str({}), '')
Пример #40
0
def _msg_uri_from_claim(base_path, msg_id, claim_id):
    return '/'.join(
        [base_path, 'messages', msg_id]
    ) + falcon.to_query_str({'claim_id': claim_id})
Пример #41
0
    def test_to_query_str_encoding(self, params, csv):
        query_str = falcon.to_query_str(params,
                                        comma_delimited_lists=csv,
                                        prefix=False)

        assert uri.parse_query_string(query_str, csv=csv) == params
Пример #42
0
def message_url(message, base_path, claim_id=None):
    path = "/".join([base_path, 'messages', message['id']])
    if claim_id:
        path += falcon.to_query_str({'claim_id': claim_id})
    return path