Python falcon.Request() Examples

The following are 30 code examples of falcon.Request(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module falcon , or try the search function .
Example #1
Source File: common.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def create_req(ctx, body):
    '''creates a falcon request'''
    env = testing.create_environ(
        path='/',
        query_string='',
        protocol='HTTP/1.1',
        scheme='http',
        host='falconframework.org',
        port=None,
        headers={'Content-Type': 'application/json'},
        app='',
        body=body,
        method='POST',
        wsgierrors=None,
        file_wrapper=None)
    req = falcon.Request(env)
    req.context = ctx
    return req 
Example #2
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_whole_serializer_validation_as_hhtp_bad_request(req):

    class TestSerializer(BaseSerializer):
        one = StringField("one different than two")
        two = StringField("two different than one")

        def validate(self, object_dict, partial=False):
            super().validate(object_dict, partial)
            # possible use case: kind of uniqueness relationship
            if object_dict['one'] == object_dict['two']:
                raise ValidationError("one must be different than two")

    class TestResource(Resource):
        serializer = TestSerializer()

    resource = TestResource()

    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'application/json'},
    )

    with pytest.raises(errors.HTTPBadRequest):
        resource.require_validated(Request(env)) 
Example #3
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_require_representation_application_json():
    resource = TestResource()

    # simple application/json content type
    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'application/json'},
    )

    representation = resource.require_representation(Request(env))
    assert isinstance(representation, dict)

    # application/json content type with charset param
    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'application/json; charset=UTF-8'},
    )

    representation = resource.require_representation(Request(env))
    assert isinstance(representation, dict) 
Example #4
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_require_representation_unsupported_media_type():
    resource = TestResource()

    # invalid content type format
    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'foo bar'},
    )

    with pytest.raises(falcon.HTTPUnsupportedMediaType):
        resource.require_representation(Request(env))

    # valid format but surely unsupported (RFC-1437)
    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'matter-transport/sentient-life-form'},
    )

    with pytest.raises(falcon.HTTPUnsupportedMediaType):
        resource.require_representation(Request(env)) 
Example #5
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_describe(req, resp):
    """
    Test if output of resource.description() has desired form.

    Args:
        req (falcon.Request): request instance object provided by ``req``
            pytest fixture
        resp (falcon.Response): responce instance provided by ``resp`` pytest
            fixture
    """
    # default description keys
    resource = Resource()
    description = resource.describe(req, resp)
    assert 'path' in description
    assert 'name' in description
    assert 'details' in description
    assert 'params' in description
    assert 'methods' in description

    # test extending of description through kwargs
    assert 'foo' not in description
    description = resource.describe(req, resp, foo='bar')
    assert 'foo' in description
    assert description['foo'] == 'bar' 
Example #6
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_required_params(req, resp):
    """
    Test that when params are missing then specific falcon exception is raised
    and thus proper status code will be returned.

    Args:
        req (falcon.Request): request instance object provided by ``req``
            pytest fixture
        resp (falcon.Response): responce instance provided by ``resp`` pytest
            fixture
    """
    class ParametrizedResource(TestResource):
        foo = StringParam(details="required foo!", required=True)

    resource = ParametrizedResource()

    with pytest.raises(errors.HTTPMissingParam):
        resource.on_get(req, resp)

    param_req = copy.copy(req)
    param_req.params['foo'] = 'bar'
    resource.on_get(req, resp)
    assert resp.status == falcon.HTTP_OK 
Example #7
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_resource_meta(req, resp):
    """
    Test if meta output part on resource GET has a desired structure

    Args:
        req (falcon.Request): request instance object provided by ``req``
            pytest fixture
        resp (falcon.Response): responce instance provided by ``resp`` pytest
            fixture
    """
    resource = TestResource()
    resource.on_get(req, resp)

    body = json.loads(resp.body)

    assert 'meta' in body
    assert 'params' in body['meta'] 
Example #8
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _retrieve_header(response, header):
    """ Little compatibility utility for response.get_header() method.

    response.get_header() was introduced in falcon 1.0 but we want to retrieve
    response header values in al versions in consitent manner.

    Args:
        response (falcon.Request): request object instance
        header (str): case-insensitive header name

    """
    try:
        return response.get_header(header)
    except AttributeError:
        # compat: on falcon<1.0 there is not get_header() method so we must
        #         access _headers dictionary directly
        # note: _headers dictionary stores headers with lower-case names but
        #       get_header is case-insensitive so make make it lowercase to
        #       ensure consistency acros versions.
        return response._headers[header.lower()] 
Example #9
Source File: authentication.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_client_address(self, req):
        """Get address from ``X-Forwarded-For`` header or use remote address.

        Remote address is used if the ``X-Forwarded-For`` header is not
        available. Note that this may not be safe to depend on both without
        proper authorization backend.

        Args:
            req (falcon.Request): falcon.Request object.

        Returns:
            str: client address.
        """
        try:
            forwarded_for = req.get_header('X-Forwarded-For', True)
            return forwarded_for.split(',')[0].strip()
        except (KeyError, HTTPMissingHeader):
            return (
                req.env.get('REMOTE_ADDR') if self.remote_address_fallback
                else None
            ) 
Example #10
Source File: base.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_options(self, req, resp, **kwargs):
        """Respond with JSON formatted resource description on OPTIONS request.

        Args:
            req (falcon.Request): Optional request object. Defaults to None.
            resp (falcon.Response): Optional response object. Defaults to None.
            kwargs (dict): Dictionary of values created by falcon from
                resource uri template.

        Returns:
            None


        .. versionchanged:: 0.2.0
           Default ``OPTIONS`` responses include ``Allow`` header with list of
           allowed HTTP methods.
        """
        resp.set_header('Allow', ', '.join(self.allowed_methods()))
        resp.body = json.dumps(self.describe(req, resp))
        resp.content_type = 'application/json' 
Example #11
Source File: mixins.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_patch(self, req, resp, handler=None, **kwargs):
        """Respond on POST HTTP request assuming resource creation flow.

        This request handler assumes that POST requests are associated with
        resource creation. Thus default flow for such requests is:

        * Create new resource instances and prepare their representation by
          calling its bulk creation method handler.
        * Set response status code to ``201 Created``.

        **Note:** this handler does not set ``Location`` header by default as
        it would be valid only for single resource creation.

        Args:
            req (falcon.Request): request object instance.
            resp (falcon.Response): response object instance to be modified
            handler (method): creation method handler to be called. Defaults
                to ``self.create``.
            **kwargs: additional keyword arguments retrieved from url template.
        """
        self.handle(
            handler or self.create_bulk, req, resp, **kwargs
        )

        resp.status = falcon.HTTP_CREATED 
Example #12
Source File: mixins.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_put(self, req, resp, handler=None, **kwargs):
        """Respond on PUT HTTP request assuming resource update flow.

        This request handler assumes that PUT requests are associated with
        resource update/modification. Thus default flow for such requests is:

        * Modify existing resource instance and prepare its representation by
          calling its update method handler.
        * Set response status code to ``202 Accepted``.

        Args:
            req (falcon.Request): request object instance.
            resp (falcon.Response): response object instance to be modified
            handler (method): update method handler to be called. Defaults
                to ``self.update``.
            **kwargs: additional keyword arguments retrieved from url template.
        """
        self.handle(
            handler or self.update, req, resp, **kwargs
        )
        resp.status = falcon.HTTP_ACCEPTED 
Example #13
Source File: mixins.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_get(self, req, resp, handler=None, **kwargs):
        """Respond on GET HTTP request assuming resource list retrieval flow.

        This request handler assumes that GET requests are associated with
        resource list retrieval. Thus default flow for such requests is:

        * Retrieve list of existing resource instances and prepare their
          representations by calling list retrieval method handler.

        Args:
            req (falcon.Request): request object instance.
            resp (falcon.Response): response object instance to be modified
            handler (method): list method handler to be called. Defaults
                to ``self.list``.
            **kwargs: additional keyword arguments retrieved from url template.
        """
        self.handle(
            handler or self.list, req, resp, **kwargs
        ) 
Example #14
Source File: test_actions_api.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def create_req(ctx, body):
    '''creates a falcon request'''
    env = testing.create_environ(
        path='/',
        query_string='',
        protocol='HTTP/1.1',
        scheme='http',
        host='falconframework.org',
        port=None,
        headers={'Content-Type': 'application/json'},
        app='',
        body=body,
        method='POST',
        wsgierrors=None,
        file_wrapper=None)
    req = falcon.Request(env)
    req.context = ctx
    return req 
Example #15
Source File: test_request_normalization.py    From flex with MIT License 6 votes vote down vote up
def test_python3_urllib_request_normalization(httpbin):
    raw_request = urllib.request.Request(
        httpbin.url + '/get',
        headers={'Content-Type': 'application/json'},
    )

    request = normalize_request(raw_request)

    assert request.path == '/get'
    assert request.content_type == 'application/json'
    assert request.url == httpbin.url + '/get'
    assert request.method == 'get'


#
# Test tornado request object
# 
Example #16
Source File: test_request_normalization.py    From flex with MIT License 6 votes vote down vote up
def test_falcon_request_normalization(httpbin):
    import falcon
    from falcon.testing.helpers import create_environ

    env = create_environ(
        path='/put',
        query_string='key=val',
        host=httpbin.host,
        port=httpbin.port,
        headers={'Content-Type': 'application/json'},
        body=b'{"key2": "val2"}',
        method='PUT',
    )
    raw_request = falcon.Request(env)

    request = normalize_request(raw_request)

    assert request.path == '/put'
    assert request.content_type == 'application/json'
    assert request.url == httpbin.url + '/put?key=val'
    assert request.method == 'put'
    assert request.body == '{"key2": "val2"}' 
Example #17
Source File: test_request_normalization.py    From flex with MIT License 6 votes vote down vote up
def test_werkzeug_request_normalization(httpbin):
    from werkzeug.test import create_environ
    from werkzeug.wrappers import Request

    env = create_environ(
        path='/put',
        base_url=httpbin.url,
        query_string='key=val',
        headers={'Content-Type': 'application/json'},
        data=b'{"key2": "val2"}',
        method='PUT',
    )
    raw_request = Request(env)
    request = normalize_request(raw_request)

    assert request.path == '/put'
    assert request.content_type == 'application/json'
    assert request.url == httpbin.url + '/put?key=val'
    assert request.method == 'put'
    assert request.data == {'key2': 'val2'} 
Example #18
Source File: mixins.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_delete(self, req, resp, handler=None, **kwargs):
        """Respond on DELETE HTTP request assuming resource deletion flow.

        This request handler assumes that DELETE requests are associated with
        resource deletion. Thus default flow for such requests is:

        * Delete existing resource instance.
        * Set response status code to ``202 Accepted``.

        Args:
            req (falcon.Request): request object instance.
            resp (falcon.Response): response object instance to be modified
            handler (method): deletion method handler to be called. Defaults
                to ``self.delete``.
            **kwargs: additional keyword arguments retrieved from url template.
        """
        self.handle(
            handler or self.delete, req, resp, **kwargs
        )

        resp.status = falcon.HTTP_ACCEPTED 
Example #19
Source File: mixins.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_get(self, req, resp, handler=None, **kwargs):
        """Respond on GET HTTP request assuming resource retrieval flow.

        This request handler assumes that GET requests are associated with
        single resource instance retrieval. Thus default flow for such requests
        is:

        * Retrieve single resource instance of prepare its representation by
          calling retrieve method handler.

        Args:
            req (falcon.Request): request object instance.
            resp (falcon.Response): response object instance to be modified
            handler (method): list method handler to be called. Defaults
                to ``self.list``.
            **kwargs: additional keyword arguments retrieved from url template.
        """
        self.handle(
            handler or self.retrieve, req, resp, **kwargs
        ) 
Example #20
Source File: request.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def __init__(self, env, options=None):
        super(Request, self).__init__(env, options)
        self.context = request_context.RequestContext.from_environ(self.env) 
Example #21
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_resource_accepts_kwargs(req, resp):
    """
    Test that on_get method accepts additional keyword arguments.
    This is important because allows passing of arguments from url template.

    Args:
        req (falcon.Request): request instance object provided by ``req``
            pytest fixture
        resp (falcon.Response): responce instance provided by ``resp`` pytest
            fixture
    """
    resource = TestResource()
    resource.on_get(req, resp, foo='bar') 
Example #22
Source File: healthcheck_api.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def on_head(self, req, res):
        """Simple healthcheck report on HEAD.

        In opposite to :py:meth:`.HealthChecksApi.on_get`, this
        method is supposed to execute ASAP to inform user that
        API is up and running.

        :param falcon.Request req: current request
        :param falcon.Response res: current response

        """
        res.status = falcon.HTTP_501 
Example #23
Source File: api.py    From graphene-mongo with MIT License 5 votes vote down vote up
def set_graphql_allow_header(
    req: falcon.Request, resp: falcon.Response, resource: object
):
    resp.set_header("Allow", "GET, POST, OPTIONS") 
Example #24
Source File: test_api_health.py    From drydock with Apache License 2.0 5 votes vote down vote up
def test_get_health(mocker, deckhand_orchestrator, drydock_state):
    api = HealthResource(
        state_manager=drydock_state, orchestrator=deckhand_orchestrator)

    # Configure mocked request and response
    req = mocker.MagicMock(spec=falcon.Request)
    resp = mocker.MagicMock(spec=falcon.Response)

    api.on_get(req, resp)

    assert resp.status == falcon.HTTP_204 
Example #25
Source File: test_api_versions.py    From drydock with Apache License 2.0 5 votes vote down vote up
def test_get_versions(mocker):
    api = VersionsResource()

    # Configure mocked request and response
    req = mocker.MagicMock(spec=falcon.Request)
    resp = mocker.MagicMock(spec=falcon.Response)

    api.on_get(req, resp)

    expected = api.to_json({'v1.0': {'path': '/api/v1.0', 'status': 'stable'}})

    assert resp.body == expected
    assert resp.status == falcon.HTTP_200 
Example #26
Source File: __init__.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def login_required(function):
    def wrapper(*args, **kwargs):
        for i, arg in enumerate(args):
            if isinstance(arg, Request):
                idx = i
                break
        req = args[idx]
        auth_token = req.get_header('AUTHORIZATION')
        if auth_token:
            authenticate_application(auth_token, req)
        else:
            authenticate_user(req)
        return function(*args, **kwargs)

    return wrapper 
Example #27
Source File: request.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def __init__(self, env, options=None):
        super(Request, self).__init__(env, options)
        self.context = request_context.RequestContext.from_environ(self.env) 
Example #28
Source File: healthcheck_api.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def on_get(self, req, res):
        """Complex healthcheck report on GET.

        Returns complex report regarding API well being
        and all dependent services.

        :param falcon.Request req: current request
        :param falcon.Response res: current response
        """
        res.status = falcon.HTTP_501 
Example #29
Source File: validation.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def validate_content_type(req, allowed):
    """Validates content type.

    Method validates request against correct
    content type.

    If content-type cannot be established (i.e. header is missing),
    :py:class:`falcon.HTTPMissingHeader` is thrown.
    If content-type is not **application/json** or **text/plain**,
    :py:class:`falcon.HTTPUnsupportedMediaType` is thrown.


    :param falcon.Request req: current request
    :param iterable allowed: allowed content type

    :exception: :py:class:`falcon.HTTPMissingHeader`
    :exception: :py:class:`falcon.HTTPUnsupportedMediaType`
    """
    content_type = req.content_type

    LOG.debug('Content-Type is %s', content_type)

    if content_type is None or len(content_type) == 0:
        raise falcon.HTTPMissingHeader('Content-Type')

    if content_type not in allowed:
        sup_types = ', '.join(allowed)
        details = ('Only [%s] are accepted as logs representations'
                   % str(sup_types))
        raise falcon.HTTPUnsupportedMediaType(description=details) 
Example #30
Source File: healthcheck_api.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def on_get(self, req, res):
        """Complex  healthcheck report on GET

        Returns complex report regarding API health
        and all dependent services

        :param falcon.Request req: current request
        :param falcon.Response res: current response
        """
        res.status = falcon.HTTP_501  # pragma: no cover