Python werkzeug.Response() Examples

The following are 18 code examples of werkzeug.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 werkzeug , or try the search function .
Example #1
Source File: rss_proxy_server.py    From rssant with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def rss_proxy_handler(request: WerkzeugRequest) -> WerkzeugResponse:
    try:
        data = json.loads(request.data.decode('utf-8'))
        assert data['token'] == _RSS_PROXY_TOKEN
        assert data.get('method') in (None, 'GET', 'POST')
        url = urlparse(data['url'])
        query = _parse_query(url.query)
        assert url.path == '/not-proxy'
        assert HTTPHeaders(data['headers'])['user-agent']
    except Exception as ex:
        LOG.warning(ex, exc_info=ex)
        msg = traceback.format_exception_only(type(ex), ex)
        return WerkzeugResponse(msg, status=400)
    status = query.get('status')
    error = query.get('error')
    if error:
        if error == 'ERROR':
            headers = {'x-rss-proxy-status': 'ERROR'}
            return WerkzeugResponse(str(status), status=200, headers=headers)
        else:
            return WerkzeugResponse(str(status), status=int(error))
    else:
        status = int(status) if status else 200
        headers = {'x-rss-proxy-status': status}
        return WerkzeugResponse(str(status), status=200, headers=headers) 
Example #2
Source File: test_reader.py    From rssant with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_read_testdata(reader_class: Type[FeedReader], httpserver: HTTPServer, filepath: str):
    filepath = _data_dir / filepath
    content = filepath.read_bytes()
    urls = []
    for i, x in enumerate(_collect_header_cases()):
        local_resp = WerkzeugResponse(content, content_type=x)
        httpserver.expect_request(f"/testdata/{i}").respond_with_response(local_resp)
        urls.append(httpserver.url_for(f"/testdata/{i}"))
    options = dict(allow_private_address=True)
    with reader_class(**options) as reader:
        for url in urls:
            response = reader.read(url)
            assert response.ok
            assert response.content == content
            assert response.encoding
            assert response.feed_type 
Example #3
Source File: plugin.py    From tensorboard with Apache License 2.0 6 votes vote down vote up
def _serve_greetings(self, request):
        """Serves greeting data for the specified tag and run.

        For details on how to use tags and runs, see
        https://github.com/tensorflow/tensorboard#tags-giving-names-to-data
        """
        run = request.args.get("run")
        tag = request.args.get("tag")
        if run is None or tag is None:
            raise werkzeug.exceptions.BadRequest("Must specify run and tag")
        try:
            data = [
                tensor_util.make_ndarray(event.tensor_proto)
                .item()
                .decode("utf-8")
                for event in self._multiplexer.Tensors(run, tag)
            ]
        except KeyError:
            raise werkzeug.exceptions.BadRequest("Invalid run or tag")
        contents = json.dumps(data, sort_keys=True)
        return werkzeug.Response(contents, content_type="application/json") 
Example #4
Source File: security_validator_test.py    From tensorboard with Apache License 2.0 6 votes vote down vote up
def make_request_and_maybe_assert_warn(
        self, headers, expected_warn_substr,
    ):
        @werkzeug.Request.application
        def _simple_app(req):
            return werkzeug.Response("OK", headers=headers)

        app = security_validator.SecurityValidatorMiddleware(_simple_app)
        server = werkzeug_test.Client(app, BaseResponse)

        with mock.patch.object(logger, "warning") as mock_warn:
            server.get("")

        if expected_warn_substr is None:
            mock_warn.assert_not_called()
        else:
            mock_warn.assert_called_with(_WARN_PREFIX + expected_warn_substr) 
Example #5
Source File: __init__.py    From choochoo with GNU General Public License v2.0 6 votes vote down vote up
def __call__(self, request, s, path):
        package, file = self.parse_path(path)
        for (extension, encoding) in (('.gz', 'gzip'), ('', None)):
            if not encoding or encoding in request.accept_encodings:
                file_extn = file + extension
                try:
                    log.debug(f'Reading {file_extn} from {package}')
                    response = Response(read_binary(package, file_extn))
                    if encoding:
                        response.content_encoding = encoding
                    self.set_content_type(response, file)
                    return response
                except Exception as e:
                    if encoding:
                        log.debug(f'Encoding {encoding} not supported by server: {e}')
                    else:
                        log.warning(f'Error serving {file}: {e}')
            else:
                log.debug(f'Encoding {encoding} not supported by client')
        raise Exception(f'File not found: {file}') 
Example #6
Source File: security_validator_test.py    From tensorboard with Apache License 2.0 5 votes vote down vote up
def test_validate_content_type(self):
        self.make_request_and_assert_no_warn(
            create_headers(content_type="application/json"),
        )

        self.make_request_and_maybe_assert_warn(
            create_headers(content_type=""),
            "Content-Type is required on a Response",
        ) 
Example #7
Source File: test_urequests.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_redirect_cpython_requests(httpserver_ipv4):
    """
    Proof that HTTP redirects work.

    This is the reference implementation using the CPython "requests" module.
    """

    httpserver = httpserver_ipv4

    # Define HTTP conversation details.
    request_data = {'hello': 'world'}
    response_data = {'status': 'ok'}

    # Mock HTTP conversation.
    def handler(request: werkzeug.Request):
        response = werkzeug.Response(status=307)
        response.headers.add('Location', '/api/v2/data')
        return response

    httpserver.expect_request("/api/v1/data").respond_with_handler(handler)
    httpserver.expect_request("/api/v2/data").respond_with_json(response_data)

    # Get URL to be invoked.
    url = httpserver.url_for("/api/v1/data")

    # Invoke HTTP request.
    requests.post(url, json=request_data)

    # Proof that worked.
    request, response = httpserver.log[0]
    assert request.get_data() == json.dumps(request_data).encode()
    assert response.status_code == 307
    assert response.get_data() == b''

    request, response = httpserver.log[1]
    assert request.get_data() == json.dumps(request_data).encode()
    assert response.status_code == 200
    assert response.get_data() == json.dumps(response_data, indent=4).encode() 
Example #8
Source File: api.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def get_data(view_func, *args, **kwargs):
    kwargs['_data_only_'] = True
    # flag this as a subrequest, so that is_browser returns False
    request.is_subrequest = True
    try:
        rv = view_func(*args, **kwargs)
    finally:
        del request.is_subrequest
    if isinstance(rv, werkzeug.Response):
        # this generally indicates that some other decorator decided to handle
        # making the response itself -- at any rate, not what we want!
        raise ValueError("cannot access data required for page")
    return rv 
Example #9
Source File: api.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def render_response(self, result, code, headers):
        json_ = json.dumps(dict(result=result), indent=4)
        tpl = render_template('api_json.html', json=json_)
        return Response(tpl, code, headers) 
Example #10
Source File: test_lib_http.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def test_response_headers_response(app, client):
    @app.route('/test')
    @http.response_headers(('foo', 'bar'))
    def response_view_func():
        return werkzeug.Response("Hello, world")
    eq_(client.get('/test').headers['foo'], 'bar') 
Example #11
Source File: __init__.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def upload_complete(digest):
    """Signal that a file has been uploaded and the server should begin
    validating it.  This is merely an optimization: the server also polls
    occasionally for uploads and validates them when they appear.

    Uploads cannot be safely validated until the upload URL has expired, which
    occurs a short time after the URL is generated (currently 60 seconds but
    subject to change).

    If the upload URL has expired, then the response is an HTTP 202 indicating
    that the signal has been accepted.  If the URL has not expired, then the
    response is an HTTP 409, and the ``X-Retry-After`` header gives a time,
    in seconds, that the client should wait before trying again."""
    if not is_valid_sha512(digest):
        raise BadRequest("Invalid sha512 digest")

    # if the pending upload is still valid, then we can't check this file
    # yet, so return 409 Conflict.  If there is no PU, or it's expired,
    # then we can proceed.
    file = tables.File.query.filter(tables.File.sha512 == digest).first()
    if file:
        for pu in file.pending_uploads:
            until = pu.expires - time.now()
            if until > datetime.timedelta(0):
                # add 1 second to avoid rounding / skew errors
                hdr = {'X-Retry-After': str(1 + int(until.total_seconds()))}
                return Response(status=409, headers=hdr)

    # start a celery task in the background and return immediately
    grooming.check_file_pending_uploads.delay(digest)
    return '{}', 202 
Example #12
Source File: wrapper.py    From flask-apispec with MIT License 5 votes vote down vote up
def __call__(self, *args, **kwargs):
        response = self.call_view(*args, **kwargs)
        if isinstance(response, werkzeug.Response):
            return response
        rv, status_code, headers = unpack(response)
        mv = self.marshal_result(rv, status_code)
        response = packed(mv, status_code, headers)
        return flask.current_app.make_response(response) 
Example #13
Source File: plugin.py    From tensorboard with Apache License 2.0 5 votes vote down vote up
def _serve_tags(self, request):
        del request  # unused
        mapping = self._multiplexer.PluginRunToTagToContent(
            metadata.PLUGIN_NAME
        )
        result = {run: {} for run in self._multiplexer.Runs()}
        for (run, tag_to_content) in six.iteritems(mapping):
            for tag in tag_to_content:
                summary_metadata = self._multiplexer.SummaryMetadata(run, tag)
                result[run][tag] = {
                    u"description": summary_metadata.summary_description,
                }
        contents = json.dumps(result, sort_keys=True)
        return werkzeug.Response(contents, content_type="application/json") 
Example #14
Source File: plugin.py    From tensorboard with Apache License 2.0 5 votes vote down vote up
def _serve_js(self, request):
        del request  # unused
        filepath = os.path.join(os.path.dirname(__file__), "static", "index.js")
        with open(filepath) as infile:
            contents = infile.read()
        return werkzeug.Response(
            contents, content_type="application/javascript"
        ) 
Example #15
Source File: test_reader.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_read_non_webpage(reader_class: Type[FeedReader], httpserver: HTTPServer, mime_type: str):
    options = dict(allow_private_address=True)
    local_resp = WerkzeugResponse(b'xxxxxxxx', mimetype=mime_type)
    httpserver.expect_request("/non-webpage").respond_with_response(local_resp)
    url = httpserver.url_for("/non-webpage")
    with reader_class(**options) as reader:
        response = reader.read(url)
        assert response.status == FeedResponseStatus.CONTENT_TYPE_NOT_SUPPORT_ERROR
        assert not response.content 
Example #16
Source File: test_reader.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_read_status(reader_class: Type[FeedReader], httpserver: HTTPServer, status: int):
    options = dict(allow_non_webpage=True, allow_private_address=True)
    local_resp = WerkzeugResponse(str(status), status=status)
    httpserver.expect_request("/status").respond_with_response(local_resp)
    url = httpserver.url_for("/status")
    with reader_class(**options) as reader:
        response = reader.read(url)
        assert response.status == status
        assert response.content == str(status).encode() 
Example #17
Source File: test_urequests.py    From terkin-datalogger with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_redirect_urequests(httpserver_ipv4):
    """
    Proof that HTTP redirects work, now based on urequests.
    """

    httpserver = httpserver_ipv4

    # Define HTTP conversation details.
    request_data = {'hello': 'world'}
    response_data = {'status': 'ok'}

    # Mock HTTP conversation.
    def handler(request: werkzeug.Request):
        response = werkzeug.Response(status=307)
        response.headers.add('Location', '/api/v2/data')
        return response

    httpserver.expect_request("/api/v1/data").respond_with_handler(handler)
    httpserver.expect_request("/api/v2/data").respond_with_json(response_data)

    # Get URL to be invoked.
    url = httpserver.url_for("/api/v1/data")

    # Invoke HTTP request.
    import urequests
    response = urequests.post(url, json=request_data)

    # Proof that worked.

    # Investigate the real response.
    assert response.content == json.dumps(response_data, indent=4).encode()

    # Investigate within the HTTP server.
    request, response = httpserver.log[0]
    assert request.get_data() == json.dumps(request_data).encode()
    assert response.status_code == 307
    assert response.get_data() == b''

    request, response = httpserver.log[1]
    assert request.get_data() == json.dumps(request_data).encode()
    assert response.status_code == 200
    assert response.get_data() == json.dumps(response_data, indent=4).encode() 
Example #18
Source File: api.py    From build-relengapi with Mozilla Public License 2.0 1 votes vote down vote up
def apimethod(return_type, *arg_types, **options):
    def wrap(wrapped):
        # adapted from wsmeext.flask (MIT-licensed)
        wsme.signature(return_type, *arg_types, **options)(wrapped)
        funcdef = wsme.api.FunctionDefinition.get(wrapped)
        funcdef.resolve_types(wsme.types.registry)

        @functools.wraps(wrapped)
        def replacement(*args, **kwargs):
            data_only = kwargs.pop('_data_only_', False)
            if data_only:
                return wrapped(*args, **kwargs)

            try:
                args, kwargs = wsme.rest.args.get_args(
                    funcdef, args, kwargs,
                    request.args, request.form,
                    request.data, request.mimetype)
            except wsme.exc.ClientSideError as e:
                raise BadRequest(e.faultstring)
            result = wrapped(*args, **kwargs)
            # if this is a Response (e.g., a redirect), just return it
            if isinstance(result, werkzeug.Response):
                return result

            # parse the result, if it was a tuple
            code = 200
            headers = {}
            if isinstance(result, tuple):
                if len(result) == 2:
                    if isinstance(result[1], dict):
                        result, headers = result
                    else:
                        result, code = result
                else:
                    result, code, headers = result
                assert 200 <= code < 299

            # convert the objects into jsonable simple types, also checking
            # the type at the same time
            result = wsme.rest.json.tojson(funcdef.return_type, result)

            # and hand to render_response, which will actually
            # generate the appropriate string form
            h = _get_handler()
            return h.render_response(result, code, headers)
        replacement.__apidoc__ = wrapped.__doc__
        return replacement
    return wrap