Python pyramid.response.Response() Examples

The following are 30 code examples of pyramid.response.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 pyramid.response , or try the search function .
Example #1
Source File: blog_api.py    From consuming_services_python_demos with MIT License 6 votes vote down vote up
def blog_post(request):
    print("Processing {} request from {} for the HTTP service: {}, ua: {}".format(
        request.method, get_ip(request), request.url, request.user_agent
    ))

    data = build_dict(request)
    post_id = data.get('post_id')

    post = MemoryDb.get_post(post_id, get_ip(request))
    if not post:
        return Response('{"error":"Post with ID not found: ' + post_id + '"}', status=404)

    return post


################################################################################
# POST /api/blog
# { blog post data... }
# 
Example #2
Source File: sentinel_view.py    From janus-cloud with GNU Affero General Public License v3.0 6 votes vote down vote up
def post_sentinel_op(request):
    params = get_params_from_request(request, op_schema)
    janus_server = request.registry.janus_server
    janus_watcher = request.registry.janus_watcher
    if params['op'] == 'start_maintenance':
        janus_server.start_maintenance()
    elif params['op'] == 'stop_maintenance':
        janus_server.stop_maintenance()
    elif params['op'] == 'restart_process':
        if janus_watcher is None:
            raise JanusCloudError('janus_watcher not enable',
                                  JANUS_ERROR_NOT_IMPLEMENTED)
        janus_watcher.stop()
        janus_watcher.start()
    else:
        raise JanusCloudError('Not implement for op {}'.format(params['op']),
                               JANUS_ERROR_NOT_IMPLEMENTED)
    return Response(status=200) 
Example #3
Source File: videoroom.py    From janus-cloud with GNU Affero General Public License v3.0 6 votes vote down vote up
def delete_videoroom_room(request):
    plugin = request.registry.videoroom_plugin
    room_mgr = plugin.room_mgr
    room_id = int(request.matchdict['room_id'])
    room_base_info = get_params_from_request(request, room_base_schema)

    room_mgr.destroy(room_id=room_id,
                     secret=room_base_info['secret'],
                     permanent=room_base_info['permanent'])

    return Response(status=200)


#@get_view(route_name='videoroom_tokens')
#def get_videoroom_tokens(request):
#    plugin = request.registry.videoroom_plugin
#    room_mgr = plugin.room_mgr
#    room_id = int(request.matchdict['room_id'])
#    room = room_mgr.get(room_id)
#    tokens_info = list(room.allowed)
#    return tokens_info 
Example #4
Source File: test_pyramid_commons.py    From n6 with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_response(self,
                      res_limits,
                      full_access,
                      is_authenticated,
                      is_cert_available,
                      expected_response):
        mocked_request = self._get_mocked_request(res_limits,
                                                  full_access,
                                                  is_authenticated,
                                                  is_cert_available)
        view_inst = self._get_view_instance(mocked_request)
        resp = view_inst.make_response()
        self.assertIsInstance(resp, Response)
        resp_body = json.loads(resp.body)
        self.assertDictEqual(resp_body, expected_response)
        self.assertEqual(resp.content_type, self.expected_content_type)
        self.assertEqual(resp.status_int, 200) 
Example #5
Source File: blog_soap.py    From consuming_services_python_demos with MIT License 6 votes vote down vote up
def get_post_response(dom, request):
    id_text = dom.find('Body/GetPost/id').text
    post = MemoryDb.get_post(id_text, get_ip(request))
    if not post:
        raise exception_response(404)

    resp_xml = """<?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
          <soap:Body>
            <GetPostResponse xmlns="http://tempuri.org/">
              <GetPostResult>
                <Id>{}</Id>
                <Title>{}</Title>
                <Published>{}</Published>
                <Content>{}</Content>
                <ViewCount>{}</ViewCount>
              </GetPostResult>
            </GetPostResponse>
          </soap:Body>
        </soap:Envelope>""".format(post.id, post.title, post.published, post.content, post.view_count)  # noqa

    return Response(body=resp_xml, content_type='text/xml') 
Example #6
Source File: blog_soap.py    From consuming_services_python_demos with MIT License 6 votes vote down vote up
def delete_post_response(dom, request):
    id_text = dom.find('Body/DeletePost/id').text
    post = MemoryDb.get_post(id_text, get_ip(request))
    if not post:
        raise exception_response(404)

    if MemoryDb.is_post_read_only(post.id):
        raise exception_response(403)

    MemoryDb.delete_post(post, get_ip(request))

    resp_xml = """<?xml version="1.0" encoding="utf-8"?>
                <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                  <soap:Body>
                    <DeletePostResponse xmlns="http://tempuri.org/" />
                  </soap:Body>
                </soap:Envelope>"""  # noqa

    return Response(body=resp_xml, content_type='text/xml') 
Example #7
Source File: data_backend_api.py    From n6 with GNU Affero General Public License v3.0 6 votes vote down vote up
def login(self, request, auth_api):
        post_data = request.POST
        try:
            user_id = post_data.getone('user_id')
            org_id = post_data.getone('org_id')
            password = post_data.getone('password')
        except KeyError as e:
            LOGGER.debug('User has not filled all credential fields for authentication. %s.',
                         e.message)
            raise HTTPForbidden
        if user_id and org_id and password:
            try:
                auth_api.authenticate_with_password(org_id, user_id, password)
            except INVALID_CREDENTIALS:
                LOGGER.warning('User tried to authenticate with invalid credentials. '
                               'User id: %r, organization id: %r.', user_id, org_id)
                raise HTTPForbidden
            credentials = self._join_org_id_user_id(org_id, user_id)
            headers = remember(request, credentials)
            self._add_content_type_header(headers)
            return Response(headerlist=headers) 
Example #8
Source File: test_pyramid.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_errorhandler_500(
    sentry_init, pyramid_config, capture_exceptions, route, get_client
):
    sentry_init(integrations=[PyramidIntegration()])
    errors = capture_exceptions()

    @route("/")
    def index(request):
        1 / 0

    def errorhandler(exc, request):
        return Response("bad request", status=500)

    pyramid_config.add_view(errorhandler, context=Exception)

    client = get_client()
    app_iter, status, headers = client.get("/")
    assert b"".join(app_iter) == b"bad request"
    assert status.lower() == "500 internal server error"

    (error,) = errors

    assert isinstance(error, ZeroDivisionError) 
Example #9
Source File: test_pyramid.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_errorhandler_ok(
    sentry_init, pyramid_config, capture_exceptions, route, get_client
):
    sentry_init(integrations=[PyramidIntegration()])
    errors = capture_exceptions()

    @route("/")
    def index(request):
        raise Exception()

    def errorhandler(exc, request):
        return Response("bad request")

    pyramid_config.add_view(errorhandler, context=Exception)

    client = get_client()
    client.get("/")

    assert not errors 
Example #10
Source File: test_pyramid.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_files_and_form(sentry_init, capture_events, route, get_client):
    sentry_init(integrations=[PyramidIntegration()], request_bodies="always")

    data = {"foo": "a" * 2000, "file": (BytesIO(b"hello"), "hello.txt")}

    @route("/")
    def index(request):
        capture_message("hi")
        return Response("ok")

    events = capture_events()

    client = get_client()
    client.post("/", data=data)

    (event,) = events
    assert event["_meta"]["request"]["data"]["foo"] == {
        "": {"len": 2000, "rem": [["!limit", "x", 509, 512]]}
    }
    assert len(event["request"]["data"]["foo"]) == 512

    assert event["_meta"]["request"]["data"]["file"] == {
        "": {"len": 0, "rem": [["!raw", "x", 0, 0]]}
    }
    assert not event["request"]["data"]["file"] 
Example #11
Source File: test_pyramid.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_flask_empty_json_request(sentry_init, capture_events, route, get_client, data):
    sentry_init(integrations=[PyramidIntegration()])

    @route("/")
    def index(request):
        assert request.json == data
        assert request.text == json.dumps(data)
        assert not request.POST
        capture_message("hi")
        return Response("ok")

    events = capture_events()

    client = get_client()
    response = client.post("/", content_type="application/json", data=json.dumps(data))
    assert response[1] == "200 OK"

    (event,) = events
    assert event["request"]["data"] == data 
Example #12
Source File: test_pyramid.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_large_json_request(sentry_init, capture_events, route, get_client):
    sentry_init(integrations=[PyramidIntegration()])

    data = {"foo": {"bar": "a" * 2000}}

    @route("/")
    def index(request):
        assert request.json == data
        assert request.text == json.dumps(data)
        assert not request.POST
        capture_message("hi")
        return Response("ok")

    events = capture_events()

    client = get_client()
    client.post("/", content_type="application/json", data=json.dumps(data))

    (event,) = events
    assert event["_meta"]["request"]["data"]["foo"]["bar"] == {
        "": {"len": 2000, "rem": [["!limit", "x", 509, 512]]}
    }
    assert len(event["request"]["data"]["foo"]["bar"]) == 512 
Example #13
Source File: test_pyramid.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_has_context(route, get_client, sentry_init, capture_events):
    sentry_init(integrations=[PyramidIntegration()])
    events = capture_events()

    @route("/message/{msg}")
    def hi2(request):
        capture_message(request.matchdict["msg"])
        return Response("hi")

    client = get_client()
    client.get("/message/yoo")

    (event,) = events
    assert event["message"] == "yoo"
    assert event["request"] == {
        "env": {"SERVER_NAME": "localhost", "SERVER_PORT": "80"},
        "headers": {"Host": "localhost"},
        "method": "GET",
        "query_string": "",
        "url": "http://localhost/message/yoo",
    }
    assert event["transaction"] == "hi2" 
Example #14
Source File: autoscaler.py    From paasta with Apache License 2.0 6 votes vote down vote up
def get_autoscaler_count(request):
    service = request.swagger_data.get("service")
    instance = request.swagger_data.get("instance")
    cluster = settings.cluster
    soa_dir = settings.soa_dir

    instance_config = get_instance_config(service, instance, cluster, soa_dir)
    if not isinstance(
        instance_config, (KubernetesDeploymentConfig, MarathonServiceConfig)
    ):
        error_message = (
            f"Autoscaling is not supported for {service}.{instance} because instance type is not "
            f"marathon or kubernetes."
        )
        raise ApiFailure(error_message, 501)

    response_body = {
        "desired_instances": instance_config.get_instances(),
        "calculated_instances": instance_config.get_instances(with_limit=False),
    }
    return Response(json_body=response_body, status_code=200) 
Example #15
Source File: __init__.py    From pyramid_openapi3 with MIT License 6 votes vote down vote up
def openapi_validation_error(
    context: t.Union[RequestValidationError, ResponseValidationError], request: Request
) -> Response:
    """Render any validation errors as JSON."""
    if isinstance(context, RequestValidationError):
        logger.warning(context)
    if isinstance(context, ResponseValidationError):
        logger.error(context)

    extract_errors = request.registry.settings["pyramid_openapi3_extract_errors"]
    errors = list(extract_errors(request, context.errors))

    # If validation failed for request, it is user's fault (-> 400), but if
    # validation failed for response, it is our fault (-> 500)
    if isinstance(context, RequestValidationError):
        status_code = 400
        for error in context.errors:
            if isinstance(error, InvalidSecurity):
                status_code = 401

    if isinstance(context, ResponseValidationError):
        status_code = 500

    return exception_response(status_code, json_body=errors) 
Example #16
Source File: test_resource.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def index(self, **a):
        return Response('index') 
Example #17
Source File: test_resource.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def get_test_view_class(name=''):
    class View(BaseView):
        _json_encoder = _JSONEncoder
        Model = mock.Mock(__name__='Foo')

        def __init__(self, *a, **k):
            BaseView.__init__(self, *a, **k)
            # turning off before and after calls
            self._before_calls = {}
            self._after_calls = {}

        def index(self, **a):
            return Response(name + 'index')

        def show(self, **a):
            return Response(name + 'show')

        def delete(self, **a):
            return Response(name + 'delete')

        def __getattr__(self, attr):
            return lambda *a, **k: Response(name + attr)

        def convert_ids2objects(self, *args, **kwargs):
            pass

        def fill_null_values(self, *args, **kwargs):
            pass

    return View 
Example #18
Source File: p2pcall.py    From janus-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def post_video_user(request):
    params = get_params_from_request(request, post_p2pcall_user_schema)
    username = request.matchdict['username']
    #print('username:', username)
    request.registry.p2pcall_plugin.handle_async_event(to_user=username, **params)
    return Response(status=200) 
Example #19
Source File: test_resource.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def show(self, **a):
        return Response('show') 
Example #20
Source File: videoroom.py    From janus-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete_videoroom_participant(request):
    plugin = request.registry.videoroom_plugin
    room_mgr = plugin.room_mgr
    room_id = int(request.matchdict['room_id'])
    user_id = int(request.matchdict['user_id'])
    room_base_info = get_params_from_request(request, room_base_schema)
    room = room_mgr.get(room_id).check_modify(room_base_info['secret'])
    room.kick_participant(user_id)

    return Response(status=200) 
Example #21
Source File: videocall.py    From janus-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def post_video_user(request):
    params = get_params_from_request(request, post_videocall_user_schema)
    username = request.matchdict['username']
    #print('username:', username)
    request.registry.videocall_plugin.call_peer(username, **params)
    return Response(status=200) 
Example #22
Source File: __init__.py    From pyramid_zipkin with Apache License 2.0 5 votes vote down vote up
def client_error(dummy_request):
    response = Response('Client Error!')
    response.status_int = 400
    return response 
Example #23
Source File: videocall.py    From janus-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def _send_backend_meseage(backend_handle, body, jsep=None):
        if backend_handle is None:
            raise JanusCloudError('Not connected', JANUS_ERROR_INTERNAL_ERROR)
        data, reply_jsep = backend_handle.send_message(body=body, jsep=jsep)
        if 'error_code' in data:
            raise JanusCloudError(data.get('error','unknown'), data['error_code'])
        elif 'result' not in data:
            raise JanusCloudError('Invalid Response payload: {}'.format(data), JANUS_ERROR_BAD_GATEWAY)
        return data['result'], reply_jsep 
Example #24
Source File: views.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def make_auth_response(self):  # type: () -> Response
        raise NotImplementedError

    #
    # Stuff accessible (also) in subclasses 
Example #25
Source File: views.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def make_response(self):
        self.validate_params()
        response = self.make_auth_response()
        assert isinstance(response, Response)
        return response

    #
    # Stuff that can or must be overridden/extended in subclasses

    # Attribute that in a subclass must be a dict that maps param
    # names (str) to `whether this param is required` flags (bool): 
Example #26
Source File: _pyramid_commons.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def plain_text_response(self, body, charset='UTF-8', **response_kwargs):
        self.__ensure_no_unwanted_kwargs(response_kwargs, 'content_type')
        self.__ensure_no_content_type_in_headerlist(response_kwargs)
        # We do not use the `content_type` keyword argument as it is ignored
        # by the `Response` constructor if non-None `headerlist` is given.
        response = Response(body, charset=charset, **response_kwargs)
        content_type = 'text/plain'
        if charset:
            content_type = '{}; {}'.format(content_type, charset)
        response.content_type = content_type
        return response


    #
    # Internal helpers 
Example #27
Source File: data_backend_api.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def logout(self, request, auth_api):
        headers = forget(request)
        self._add_content_type_header(headers)
        return Response(headerlist=headers) 
Example #28
Source File: data_backend_api.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def login_with_cert(self, request, auth_api):
        org_id, user_id = get_certificate_credentials(request)
        try:
            auth_api.authenticate(org_id, user_id)
        except AuthAPIUnauthenticatedError:
            LOGGER.warning('Could not authenticate with certificate for '
                           'organization id %r + user id %r.', org_id, user_id)
            raise HTTPForbidden
        else:
            credentials = self._join_org_id_user_id(org_id, user_id)
            headers = remember(request, credentials)
            self._add_content_type_header(headers)
            return Response(headerlist=headers) 
Example #29
Source File: data_backend_api.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_user_info(self,
                      is_authenticated,
                      available_resources=None,
                      full_access=False,
                      certificate_fetched=False):
        body = {
            'authenticated': is_authenticated,
            'certificate_fetched': certificate_fetched,
        }
        if is_authenticated:
            body['available_resources'] = available_resources
            if full_access:
                body['full_access'] = full_access
        serialized_body = json.dumps(body)
        return Response(serialized_body, content_type='application/json') 
Example #30
Source File: blog_api.py    From consuming_services_python_demos with MIT License 5 votes vote down vote up
def delete_blog_post(request):
    print("Processing {} request from {} for the HTTP service: {}, ua: {}".format(
        request.method, get_ip(request), request.url, request.user_agent
    ))

    data = build_dict(request)
    post_id = data.get('post_id')

    if MemoryDb.is_post_read_only(post_id):
        return Response('{"error":"The post with id ' + str(post_id) +
                        ' is read-only. '
                        'You can only delete posts that you have created yourself via this API."}',
                        status=403)

    post = MemoryDb.get_post(post_id, get_ip(request))
    if not post:
        return Response('{"error":"Post with ID not found: ' + post_id + '"}', status=404)

    MemoryDb.delete_post(post, get_ip(request))
    request.response.status_code = 202

    return {'deleted': post_id}


################################################################################
# GET /api/reset
#