Python falcon.Response() Examples
The following are 30
code examples of falcon.Response().
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: base.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
def make_body(self, resp, params, meta, content): """Construct response body in ``resp`` object using JSON serialization. Args: resp (falcon.Response): response object where to include serialized body params (dict): dictionary of parsed parameters meta (dict): dictionary of metadata to be included in 'meta' section of response content (dict): dictionary of response content (resource representation) to be included in 'content' section of response Returns: None """ response = { 'meta': meta, 'content': content } resp.content_type = 'application/json' resp.body = json.dumps( response, indent=params['indent'] or None if 'indent' in params else None )
Example #2
Source File: test_auth_middleware.py From drydock with Apache License 2.0 | 6 votes |
def test_process_request_user(self): ''' AuthMiddleware is expected to correctly identify the headers added to an authenticated request by keystonemiddleware in a PasteDeploy configuration ''' req_env = TestAuthMiddleware.ks_user_env project_id = str(uuid.uuid4().hex) req_env['HTTP_X_PROJECT_ID'] = project_id user_id = str(uuid.uuid4().hex) req_env['HTTP_X_USER_ID'] = user_id token = str(uuid.uuid4().hex) req_env['HTTP_X_AUTH_TOKEN'] = token middleware = AuthMiddleware() request = DrydockRequest(req_env) response = falcon.Response() middleware.process_request(request, response) assert request.context.authenticated assert request.context.user_id == user_id
Example #3
Source File: test_auth_middleware.py From drydock with Apache License 2.0 | 6 votes |
def test_process_request_user_noauth(self): ''' AuthMiddleware is expected to correctly identify the headers added to an unauthenticated (no token, bad token) request by keystonemiddleware in a PasteDeploy configuration ''' req_env = TestAuthMiddleware.ks_user_env req_env['HTTP_X_IDENTITY_STATUS'] = 'Invalid' middleware = AuthMiddleware() request = DrydockRequest(req_env) response = falcon.Response() middleware.process_request(request, response) assert request.context.authenticated is False
Example #4
Source File: test_resources.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #5
Source File: test_resources.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #6
Source File: test_resources.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #7
Source File: test_resources.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_base_resource_get(req, resp): """ Test that simple resource GET will return 200 OK response with JSON encoded body. 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) assert resp.content_type == "application/json" assert resp.body assert resp.status == falcon.HTTP_200
Example #8
Source File: authentication.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_user( self, identified_with, identifier, req, resp, resource, uri_kwargs ): """Get user from the storage. Args: identified_with (str): instance of the authentication middleware that provided the ``identifier`` value. identifier (str): string that identifies the user (it is specific for every authentication middleware implementation). req (falcon.Request): the request object. resp (falcon.Response): the response object. resource (object): the resource object. uri_kwargs (dict): keyword arguments from the URI template. Returns: the deserialized user object. Preferably a ``dict`` but it is application-specific. """ raise NotImplementedError # pragma: nocover
Example #9
Source File: base.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #10
Source File: mixins.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #11
Source File: mixins.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #12
Source File: mixins.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #13
Source File: mixins.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
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: mixins.py From graceful with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #15
Source File: test_auth_middleware.py From drydock with Apache License 2.0 | 6 votes |
def test_process_request_user_noauth(self): ''' AuthMiddleware is expected to correctly identify the headers added to an unauthenticated (no token, bad token) request by keystonemiddleware in a PasteDeploy configuration ''' req_env = TestAuthMiddleware.ks_user_env req_env['HTTP_X_IDENTITY_STATUS'] = 'Invalid' middleware = AuthMiddleware() request = DrydockRequest(req_env) response = falcon.Response() middleware.process_request(request, response) assert request.context.authenticated is False
Example #16
Source File: test_auth_middleware.py From drydock with Apache License 2.0 | 6 votes |
def test_process_request_user(self): ''' AuthMiddleware is expected to correctly identify the headers added to an authenticated request by keystonemiddleware in a PasteDeploy configuration ''' req_env = TestAuthMiddleware.ks_user_env project_id = str(uuid.uuid4().hex) req_env['HTTP_X_PROJECT_ID'] = project_id user_id = str(uuid.uuid4().hex) req_env['HTTP_X_USER_ID'] = user_id token = str(uuid.uuid4().hex) req_env['HTTP_X_AUTH_TOKEN'] = token middleware = AuthMiddleware() request = DrydockRequest(req_env) response = falcon.Response() middleware.process_request(request, response) assert request.context.authenticated assert request.context.user_id == user_id
Example #17
Source File: common.py From shipyard with Apache License 2.0 | 5 votes |
def create_resp(): '''creates a falcon response''' resp = falcon.Response() return resp
Example #18
Source File: healthcheck_api.py From monasca-log-api with Apache License 2.0 | 5 votes |
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 #19
Source File: healthcheck_api.py From monasca-api with Apache License 2.0 | 5 votes |
def on_head(self, req, res): """Simple healthcheck report on HEAD. In opposite to :py:meth:`.HealthCheckApi.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 # pragma: no cover
Example #20
Source File: healthcheck_api.py From monasca-api with Apache License 2.0 | 5 votes |
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
Example #21
Source File: healthcheck_api.py From monasca-log-api with Apache License 2.0 | 5 votes |
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 #22
Source File: test_actions_api.py From shipyard with Apache License 2.0 | 5 votes |
def create_resp(): '''creates a falcon response''' resp = falcon.Response() return resp
Example #23
Source File: test_actions_api.py From shipyard with Apache License 2.0 | 5 votes |
def test_invoke_airflow_dag_errors(mock_info): act_resource = ActionsResource() dag_id = 'test_dag_id' action = {'id': '123', 'user': 'unittester'} web_server_url = CONF.base.web_server conf_value = {'action': action} responses.add( method='POST', url='{}api/experimental/dags/{}/dag_runs'.format( web_server_url, dag_id), body=json.dumps({ "error": "not found" }), status=404, content_type='application/json') with pytest.raises(ApiError) as expected_exc: act_resource.invoke_airflow_dag(dag_id, action, context) mock_info.assert_called_with('Response code from Airflow trigger_dag: %s', 404) assert 'Unable to complete request to Airflow' in str(expected_exc) assert 'Airflow could not be contacted properly by Shipyard' in str( expected_exc) with mock.patch.object(actions_api, 'CONF') as mock_conf: mock_conf.base.web_server = 'Error' with pytest.raises(ApiError) as expected_exc: act_resource.invoke_airflow_dag(dag_id, action, context) assert 'Unable to invoke workflow' in str(expected_exc) assert ('Airflow URL not found by Shipyard. Shipyard configuration is ' 'missing web_server value') in str(expected_exc)
Example #24
Source File: test_api_health.py From drydock with Apache License 2.0 | 5 votes |
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 |
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: test_api_health.py From drydock with Apache License 2.0 | 5 votes |
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 #27
Source File: api.py From graphene-mongo with MIT License | 5 votes |
def set_graphql_allow_header( req: falcon.Request, resp: falcon.Response, resource: object ): resp.set_header("Allow", "GET, POST, OPTIONS")
Example #28
Source File: test_resources.py From graceful with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_options(resp): """ Test that options is a json serialized output of resource.describe() Args: req (falcon.Request): request instance object provided by ``req`` pytest fixture resp (falcon.Response): responce instance provided by ``resp`` pytest fixture """ # note: creating request is optional here since we bypass whole falcon # routing and dispatching procedure env = create_environ(method="OPTIONS") req = Request(env) # noqa resource = Resource() resource.on_options(req, resp) assert all([ 'OPTIONS' in _retrieve_header(resp, 'allow'), 'GET' in _retrieve_header(resp, 'allow'), ]) assert resp.status == falcon.HTTP_200 assert json.loads(resp.body) # assert this is obviously the same assert resource.describe(req, resp) == json.loads(resp.body)
Example #29
Source File: fixtures.py From graceful with BSD 3-Clause "New" or "Revised" License | 5 votes |
def resp(): """Simple empty Response fixture.""" return Response()
Example #30
Source File: authentication.py From graceful with BSD 3-Clause "New" or "Revised" License | 5 votes |
def identify(self, req, resp, resource, uri_kwargs): """Identify the user that made the request. Args: req (falcon.Request): request object resp (falcon.Response): response object resource (object): resource object matched by falcon router uri_kwargs (dict): additional keyword argument from uri template. For ``falcon<1.0.0`` this is always ``None`` Returns: object: a user object (preferably a dictionary). """ raise NotImplementedError # pragma: nocover