Python webob.Response() Examples

The following are 30 code examples of webob.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 webob , or try the search function .
Example #1
Source File: s3server.py    From ec2-api with Apache License 2.0 7 votes vote down vote up
def __call__(self, request):
        try:
            method = request.method.lower()
            f = getattr(self, method, self.invalid)
            self.request = request
            self.response = webob.Response()
            params = request.environ['wsgiorg.routing_args'][1]
            del params['controller']
            f(**params)
        except Exception:
            # TODO(andrey-mp): improve this block
            LOG.exception('Unhandled error')
            self.render_xml({"Error": {
                "Code": "BadRequest",
                "Message": "Unhandled error"
            }})
            self.set_status(501)

        return self.response 
Example #2
Source File: mixins.py    From xblock-video with GNU General Public License v3.0 6 votes vote down vote up
def download_transcript(self, request, _suffix=''):
        """
        Download a transcript.

        Arguments:
            request (webob.Request): Request to handle.
            suffix (string): Slug used for routing.
        Returns:
            File with the correct name.
        """
        trans_path = self.get_path_for(request.query_string)
        filename = self.get_file_name_from_path(trans_path)
        transcript = requests.get(request.host_url + request.query_string).text
        response = Response(transcript)
        headerlist = [
            ('Content-Type', 'text/plain'),
            ('Content-Disposition', 'attachment; filename={}'.format(filename))
        ]
        response.headerlist = headerlist
        return response 
Example #3
Source File: wsgi.py    From manila with Apache License 2.0 6 votes vote down vote up
def serialize(self, request, content_type, default_serializers=None):
        """Serializes the wrapped object.

        Utility method for serializing the wrapped object.  Returns a
        webob.Response object.
        """

        if self.serializer:
            serializer = self.serializer
        else:
            _mtype, _serializer = self.get_serializer(content_type,
                                                      default_serializers)
            serializer = _serializer()

        response = webob.Response()
        response.status_int = self.code
        for hdr, value in self._headers.items():
            response.headers[hdr] = six.text_type(value)
        response.headers['Content-Type'] = six.text_type(content_type)
        if self.obj is not None:
            response.body = serializer.serialize(self.obj)

        return response 
Example #4
Source File: share_servers.py    From manila with Apache License 2.0 6 votes vote down vote up
def delete(self, req, id):
        """Delete specified share server."""
        context = req.environ['manila.context']
        try:
            share_server = db_api.share_server_get(context, id)
        except exception.ShareServerNotFound as e:
            raise exc.HTTPNotFound(explanation=e.msg)
        allowed_statuses = [constants.STATUS_ERROR, constants.STATUS_ACTIVE]
        if share_server['status'] not in allowed_statuses:
            data = {
                'status': share_server['status'],
                'allowed_statuses': allowed_statuses,
            }
            msg = _("Share server's actual status is %(status)s, allowed "
                    "statuses for deletion are %(allowed_statuses)s.") % (data)
            raise exc.HTTPForbidden(explanation=msg)
        LOG.debug("Deleting share server with id: %s.", id)
        try:
            self.share_api.delete_share_server(context, share_server)
        except exception.ShareServerInUse as e:
            raise exc.HTTPConflict(explanation=e.msg)
        return webob.Response(status_int=http_client.ACCEPTED) 
Example #5
Source File: share_types_extra_specs.py    From manila with Apache License 2.0 6 votes vote down vote up
def _delete(self, req, type_id, id):
        """Deletes an existing extra spec."""
        context = req.environ['manila.context']

        if id in share_types.get_required_extra_specs():
            msg = _("Extra spec '%s' can't be deleted.") % id
            raise webob.exc.HTTPForbidden(explanation=msg)

        try:
            db.share_type_extra_specs_delete(context, type_id, id)
        except exception.ShareTypeExtraSpecsNotFound as error:
            raise webob.exc.HTTPNotFound(explanation=error.msg)

        notifier_info = dict(type_id=type_id, id=id)
        notifier = rpc.get_notifier('shareTypeExtraSpecs')
        notifier.info(context, 'share_type_extra_specs.delete', notifier_info)
        return webob.Response(status_int=http_client.ACCEPTED) 
Example #6
Source File: share_metadata.py    From manila with Apache License 2.0 6 votes vote down vote up
def delete(self, req, share_id, id):
        """Deletes an existing metadata."""
        context = req.environ['manila.context']

        metadata = self._get_metadata(context, share_id)

        if id not in metadata:
            msg = _("Metadata item was not found")
            raise exc.HTTPNotFound(explanation=msg)

        try:
            share = self.share_api.get(context, share_id)
            self.share_api.delete_share_metadata(context, share, id)
        except exception.NotFound:
            msg = _('share does not exist')
            raise exc.HTTPNotFound(explanation=msg)
        return webob.Response(status_int=http_client.OK) 
Example #7
Source File: app.py    From pledgeservice with Apache License 2.0 6 votes vote down vote up
def __init__(self, message, *args):
        if isinstance(message, binary_type):
            message = message.decode('utf8')
        str_args = ()
        for arg in args:
            if isinstance(arg, webob.Response):
                body = arg.body
                if isinstance(body, binary_type):
                    if arg.charset:
                        arg = body.decode(arg.charset)
                    else:
                        arg = repr(body)
            elif isinstance(arg, binary_type):
                try:
                    arg = arg.decode('utf8')
                except UnicodeDecodeError:
                    arg = repr(arg)
            str_args += (arg,)
        message = message % str_args
        Exception.__init__(self, message) 
Example #8
Source File: server.py    From octavia with Apache License 2.0 6 votes vote down vote up
def upload_config(self):
        try:
            stream = flask.request.stream
            file_path = cfg.find_config_files(project=CONF.project,
                                              prog=CONF.prog)[0]
            flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
            # mode 00600
            mode = stat.S_IRUSR | stat.S_IWUSR
            with os.fdopen(os.open(file_path, flags, mode), 'wb') as cfg_file:
                b = stream.read(BUFFER)
                while b:
                    cfg_file.write(b)
                    b = stream.read(BUFFER)

            CONF.mutate_config_files()
        except Exception as e:
            LOG.error("Unable to update amphora-agent configuration: "
                      "{}".format(str(e)))
            return webob.Response(json=dict(
                message="Unable to update amphora-agent configuration.",
                details=str(e)), status=500)

        return webob.Response(json={'message': 'OK'}, status=202) 
Example #9
Source File: http.py    From pledgeservice with Apache License 2.0 6 votes vote down vote up
def wrapper(self, environ, start_response):
        """Wrap the wsgi application to override some path:

        ``/__application__``: allow to ping the server.

        ``/__file__?__file__={path}``: serve the file found at ``path``
        """
        if '__file__' in environ['PATH_INFO']:
            req = webob.Request(environ)
            resp = webob.Response()
            resp.content_type = 'text/html; charset=UTF-8'
            filename = req.params.get('__file__')
            if os.path.isfile(filename):
                body = open(filename, 'rb').read()
                body = body.replace(six.b('http://localhost/'),
                                    six.b('http://%s/' % req.host))
                resp.body = body
            else:
                resp.status = '404 Not Found'
            return resp(environ, start_response)
        elif '__application__' in environ['PATH_INFO']:
            return webob.Response('server started')(environ, start_response)
        return self.test_app(environ, start_response) 
Example #10
Source File: lti_xblock.py    From xblock-lti-consumer with GNU Affero General Public License v3.0 6 votes vote down vote up
def lti_1p3_launch_handler(self, request, suffix=''):  # pylint: disable=unused-argument
        """
        XBlock handler for launching the LTI 1.3 tools.

        Displays a form with the OIDC preflight request and
        submits it to the tool.

        Arguments:
            request (xblock.django.request.DjangoWebobRequest): Request object for current HTTP request

        Returns:
            webob.response: HTML LTI launch form
        """
        lti_consumer = self._get_lti1p3_consumer()
        context = lti_consumer.prepare_preflight_url(
            callback_url=get_lms_lti_launch_link(),
            hint=str(self.location),  # pylint: disable=no-member
            lti_hint=str(self.location)  # pylint: disable=no-member
        )

        loader = ResourceLoader(__name__)
        template = loader.render_mako_template('/templates/html/lti_1p3_oidc.html', context)
        return Response(template, content_type='text/html') 
Example #11
Source File: shares.py    From manila with Apache License 2.0 6 votes vote down vote up
def _deny_access(self, req, id, body):
        """Remove share access rule."""
        context = req.environ['manila.context']

        access_id = body.get(
            'deny_access', body.get('os-deny_access'))['access_id']

        try:
            access = self.share_api.access_get(context, access_id)
            if access.share_id != id:
                raise exception.NotFound()
            share = self.share_api.get(context, id)
        except exception.NotFound as error:
            raise webob.exc.HTTPNotFound(explanation=six.text_type(error))
        self.share_api.deny_access(context, share, access)
        return webob.Response(status_int=http_client.ACCEPTED) 
Example #12
Source File: loadbalancer.py    From octavia with Apache License 2.0 6 votes vote down vote up
def get_all_listeners_status(self, other_listeners=None):
        """Gets the status of all listeners

        This method will not consult the stats socket
        so a listener might show as ACTIVE but still be
        in ERROR

        Currently type==SSL is also not detected
        """
        listeners = list()

        for lb in util.get_loadbalancers():
            stats_socket, listeners_on_lb = util.parse_haproxy_file(lb)

            for listener_id, listener in listeners_on_lb.items():
                listeners.append({
                    'status': consts.ACTIVE,
                    'uuid': listener_id,
                    'type': listener['mode'],
                })

        if other_listeners:
            listeners = listeners + other_listeners
        return webob.Response(json=listeners, content_type='application/json') 
Example #13
Source File: app.py    From firefly with Apache License 2.0 6 votes vote down vote up
def process_request(self, request):
        if request.method == 'OPTIONS':
            response = Response(status='200 OK', body=b'')
            response.headerlist += self._prepare_cors_headers()
            return response

        if not self.verify_auth_token(request):
            return self.http_error('403 Forbidden', error='Invalid auth token')

        # Clear all the existing state, if any
        ctx.__dict__.clear()

        ctx.request = request

        path = request.path_info
        if path in self.mapping:
            func = self.mapping[path]
            response = func(request)
            response.headerlist += self._prepare_cors_headers()
        else:
            response = self.http_error('404 Not Found', error="Not found: " + path)

        ctx.request = None
        return response 
Example #14
Source File: plug.py    From octavia with Apache License 2.0 6 votes vote down vote up
def _interface_by_mac(self, mac):
        try:
            with pyroute2.IPRoute() as ipr:
                idx = ipr.link_lookup(address=mac)[0]
                addr = ipr.get_links(idx)[0]
                for attr in addr['attrs']:
                    if attr[0] == 'IFLA_IFNAME':
                        return attr[1]
        except Exception as e:
            LOG.info('Unable to find interface with MAC: %s, rescanning '
                     'and returning 404. Reported error: %s', mac, str(e))

        # Poke the kernel to re-enumerate the PCI bus.
        # We have had cases where nova hot plugs the interface but
        # the kernel doesn't get the memo.
        filename = '/sys/bus/pci/rescan'
        flags = os.O_WRONLY
        if os.path.isfile(filename):
            with os.fdopen(os.open(filename, flags), 'w') as rescan_file:
                rescan_file.write('1')
        raise exceptions.HTTPException(
            response=webob.Response(json=dict(
                details="No suitable network interface found"), status=404)) 
Example #15
Source File: test_mixins.py    From xblock-video with GNU General Public License v3.0 6 votes vote down vote up
def test_srt_to_vtt(self, convert_caps_to_vtt_mock, requests_mock):
        """
        Test xBlock's srt-to-vtt convertation works properly.
        """
        # Arrange
        request_mock = MagicMock()
        convert_caps_to_vtt_mock.return_value = 'vtt transcripts'
        requests_mock.get.return_value.text = text_mock = PropertyMock()
        text_mock.return_value = 'vtt transcripts'

        # Act
        vtt_response = self.xblock.srt_to_vtt(request_mock, 'unused suffix')

        # Assert
        self.assertIsInstance(vtt_response, Response)
        self.assertEqual(vtt_response.text, 'vtt transcripts')
        convert_caps_to_vtt_mock.assert_called_once_with(text_mock) 
Example #16
Source File: test_mixins.py    From xblock-video with GNU General Public License v3.0 6 votes vote down vote up
def test_download_transcript_handler_response_object(self, get_mock, get_filename_mock):
        """
        Test transcripts downloading works properly.
        """
        # Arrange
        get_filename_mock.return_value = 'transcript.vtt'
        get_mock.return_value.text = 'vtt transcripts'
        request_mock = MagicMock()
        request_mock.host_url = 'test.host'
        request_mock.query_string = '/test-query-string'

        # Act
        vtt_response = self.xblock.download_transcript(request_mock, 'unused suffix')

        # Assert
        self.assertIsInstance(vtt_response, Response)
        self.assertEqual(vtt_response.text, 'vtt transcripts')
        self.assertEqual(vtt_response.headerlist, [
            ('Content-Type', 'text/plain'),
            ('Content-Disposition', 'attachment; filename={}'.format('transcript.vtt'))
        ])
        get_mock.assert_called_once_with('test.host/test-query-string') 
Example #17
Source File: test_response_normalization.py    From flex with MIT License 6 votes vote down vote up
def test_webob_response_normalization(httpbin):
    import webob

    raw_request = webob.Request.blank(httpbin.url + '/get')
    raw_request.query_string = 'key=val'
    raw_request.method = 'GET'
    raw_request.content_type = 'application/json'

    raw_response = webob.Response()
    raw_response.content_type = 'application/json'

    response = normalize_response(raw_response, raw_request)

    assert response.path == '/get'
    assert response.content_type == 'application/json'
    assert response.url == httpbin.url + '/get?key=val'
    assert response.status_code == '200' 
Example #18
Source File: test_response_normalization.py    From flex with MIT License 6 votes vote down vote up
def test_werkzeug_response_normalization(httpbin):
    from werkzeug.wrappers import Request, Response
    from werkzeug.test import create_environ

    raw_request = Request(create_environ(
        path='/get',
        base_url=httpbin.url,
        query_string='key=val',
        method='GET',
    ))

    raw_response = Response(
        response=b'{"key2": "val2"}',
        content_type='application/json',
    )

    response = normalize_response(raw_response, raw_request)

    assert response.path == '/get'
    assert response.content_type == 'application/json'
    assert response.url == httpbin.url + '/get?key=val'
    assert response.status_code == '200' 
Example #19
Source File: http.py    From flex with MIT License 6 votes vote down vote up
def _normalize_django_response(response, request=None):
    if not _django_available:
        raise TypeError("django is not installed")

    if not isinstance(response, (django.http.response.HttpResponse)):
        raise TypeError("Cannot normalize this request object")

    url = None

    if isinstance(response, django.http.response.HttpResponseRedirect):
        url = response.url
    elif request:
        url = request.url
    else:
        raise TypeError("Normalized django object needs a path")

    return Response(
        request=request,
        content=response.content,
        url=url,
        status_code=response.status_code,
        content_type=response.get('Content-Type'),
        response=response) 
Example #20
Source File: http.py    From flex with MIT License 6 votes vote down vote up
def _normalize_requests_response(response, request=None):
    import requests
    if not isinstance(response, requests.Response):
        raise TypeError("Cannot normalize this response object")

    url = response.url
    status_code = response.status_code
    content_type = response.headers.get('Content-Type')

    return Response(
        request=request,
        content=response.content,
        url=url,
        status_code=status_code,
        content_type=content_type,
        response=response,
    ) 
Example #21
Source File: http.py    From flex with MIT License 6 votes vote down vote up
def _normalize_urllib_response(response, request=None):
    if six.PY2:
        if not isinstance(response, urllib.addinfourl):
            raise TypeError("Cannot normalize this response object")
    else:
        if not isinstance(response, http.client.HTTPResponse):
            raise TypeError("Cannot normalize this response object")

    url = response.url
    status_code = response.getcode()
    content_type = response.headers.get('Content-Type')

    return Response(
        request=request,
        content=response.read(),
        url=url,
        status_code=status_code,
        content_type=content_type,
        response=response,
    ) 
Example #22
Source File: http.py    From flex with MIT License 6 votes vote down vote up
def _normalize_webob_response(response, request=None):
    if not _webob_available:
        raise TypeError("webob is not installed")

    if not isinstance(response, webob.Response):
        raise TypeError("Cannot normalize this response object")

    url = None

    if request:
        url = request.url
    elif response.request:
        url = response.request.url
    else:
        raise TypeError("Normalized webob object needs a path")

    return Response(
        request=request,
        content=response.body,
        url=url,
        status_code=response.status.split()[0],
        content_type=response.content_type,
        response=response,
    ) 
Example #23
Source File: http.py    From flex with MIT License 6 votes vote down vote up
def _normalize_werkzeug_response(response, request=None):
    if not _werkzeug_available:
        raise TypeError("werkzeug is not installed")

    if not isinstance(response, werkzeug.wrappers.BaseResponse):
        raise TypeError("Cannot normalize this response object")

    if request is None:
        raise TypeError("Cannot normalize this response object")

    return Response(
        url=request.url,
        request=request,
        content=response.data,
        status_code=response.status_code,
        content_type=response.headers.get('Content-Type'),
        response=response,
    ) 
Example #24
Source File: http.py    From flex with MIT License 6 votes vote down vote up
def normalize_response(response, request=None):
    """
    Given a response, normalize it to the internal Response class.  This also
    involves normalizing the associated request object.
    """
    if isinstance(response, Response):
        return response
    if request is not None and not isinstance(request, Request):
        request = normalize_request(request)

    for normalizer in RESPONSE_NORMALIZERS:
        try:
            return normalizer(response, request=request)
        except TypeError:
            continue

    raise ValueError("Unable to normalize the provided response") 
Example #25
Source File: mixins.py    From xblock-video with GNU General Public License v3.0 6 votes vote down vote up
def fetch_from_three_play_media(self, request, _suffix=''):
        """
        Proxy handler to hide real API url.

        Arguments:
            request (webob.Request): The request to handle
            suffix (string): not used
            query string: 'language_id=transcript_id'
        Returns:
            webob.Response: WebVTT transcripts wrapped in Response object.
        """
        lang_id, transcript_id = request.query_string.split('=')
        transcript = self.fetch_single_3pm_translation(transcript_data={'id': transcript_id, 'language_id': lang_id})
        if transcript is None:
            return Response()
        return Response(transcript.content, content_type='text/vtt') 
Example #26
Source File: loadbalancer.py    From octavia with Apache License 2.0 6 votes vote down vote up
def upload_certificate(self, lb_id, filename):
        self._check_ssl_filename_format(filename)

        # create directory if not already there
        if not os.path.exists(self._cert_dir(lb_id)):
            os.makedirs(self._cert_dir(lb_id))

        stream = Wrapped(flask.request.stream)
        file = self._cert_file_path(lb_id, filename)
        flags = os.O_WRONLY | os.O_CREAT
        # mode 00600
        mode = stat.S_IRUSR | stat.S_IWUSR
        with os.fdopen(os.open(file, flags, mode), 'wb') as crt_file:
            b = stream.read(BUFFER)
            while b:
                crt_file.write(b)
                b = stream.read(BUFFER)

        resp = webob.Response(json=dict(message='OK'))
        resp.headers['ETag'] = stream.get_md5()
        return resp 
Example #27
Source File: mixins.py    From xblock-video with GNU General Public License v3.0 5 votes vote down vote up
def srt_to_vtt(self, request, _suffix=''):
        """
        Fetch raw transcripts, convert them into WebVTT format and return back.

        Path to raw transcripts is passed in as `request.query_string`.

        Arguments:
            request (webob.Request): The request to handle
            suffix (string): The remainder of the url, after the handler url prefix, if available.
        Returns:
            webob.Response: WebVTT transcripts wrapped in Response object.
        """
        caps_path = request.query_string
        caps = requests.get(request.host_url + caps_path).text
        return Response(self.convert_caps_to_vtt(caps)) 
Example #28
Source File: mixins.py    From xblock-video with GNU General Public License v3.0 5 votes vote down vote up
def validate_three_play_media_config(self, request, _suffix=''):
        """
        Handler to validate provided API credentials.

        Arguments:
            request (webob.Request):
            suffix (string): not used
        Returns:
            webob.Response: (json) {'isValid': true/false}
        """
        api_key = request.json.get('api_key')
        file_id = request.json.get('file_id')
        streaming_enabled = bool(int(request.json.get('streaming_enabled')))  # streaming_enabled is expected to be "1"

        is_valid = True
        success_message = _('Success')
        invalid_message = _('Check provided 3PlayMedia configuration')

        # the very first request during xblock creating:
        if api_key is None and file_id is None:
            return Response(json={'isValid': is_valid, 'message': _("Initialization")})

        # the case when no options provided, and streaming is disabled:
        if not streaming_enabled:
            return Response(json={'isValid': is_valid, 'message': success_message})

        # options partially provided or both empty, but streaming is enabled:
        if not (api_key and file_id):
            is_valid = False
            return Response(json={'isValid': is_valid, 'message': invalid_message})

        feedback, transcripts_list = self.get_3pm_transcripts_list(file_id, api_key)

        if transcripts_list and feedback['status'] is Status.success:
            message = success_message
            is_valid = True
        else:
            message = feedback['message']
            is_valid = False

        return Response(json={'isValid': is_valid, 'message': message}) 
Example #29
Source File: share_group_types.py    From manila with Apache License 2.0 5 votes vote down vote up
def _add_project_access(self, req, id, body):
        context = req.environ['manila.context']
        self._check_body(body, 'addProjectAccess')
        project = body['addProjectAccess']['project']
        self._assert_non_public_share_group_type(context, id)
        try:
            share_group_types.add_share_group_type_access(
                context, id, project)
        except exception.ShareGroupTypeAccessExists as err:
            raise webob.exc.HTTPConflict(explanation=six.text_type(err))
        return webob.Response(status_int=http_client.ACCEPTED)

    # pylint: enable=function-redefined 
Example #30
Source File: share_snapshots.py    From manila with Apache License 2.0 5 votes vote down vote up
def delete(self, req, id):
        """Delete a snapshot."""
        context = req.environ['manila.context']

        LOG.info("Delete snapshot with id: %s", id, context=context)

        try:
            snapshot = self.share_api.get_snapshot(context, id)
            self.share_api.delete_snapshot(context, snapshot)
        except exception.NotFound:
            raise exc.HTTPNotFound()
        return webob.Response(status_int=http_client.ACCEPTED)