当前位置: 首页>>代码示例>>Python>>正文


Python werkzeug.Response方法代码示例

本文整理汇总了Python中werkzeug.Response方法的典型用法代码示例。如果您正苦于以下问题:Python werkzeug.Response方法的具体用法?Python werkzeug.Response怎么用?Python werkzeug.Response使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在werkzeug的用法示例。


在下文中一共展示了werkzeug.Response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: rss_proxy_handler

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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) 
开发者ID:anyant,项目名称:rssant,代码行数:27,代码来源:rss_proxy_server.py

示例2: test_read_testdata

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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 
开发者ID:anyant,项目名称:rssant,代码行数:18,代码来源:test_reader.py

示例3: _serve_greetings

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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") 
开发者ID:tensorflow,项目名称:tensorboard,代码行数:23,代码来源:plugin.py

示例4: make_request_and_maybe_assert_warn

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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) 
开发者ID:tensorflow,项目名称:tensorboard,代码行数:19,代码来源:security_validator_test.py

示例5: __call__

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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}') 
开发者ID:andrewcooke,项目名称:choochoo,代码行数:22,代码来源:__init__.py

示例6: __call__

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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) 
开发者ID:jmcarp,项目名称:flask-apispec,代码行数:10,代码来源:wrapper.py

示例7: test_read_status

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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() 
开发者ID:anyant,项目名称:rssant,代码行数:11,代码来源:test_reader.py

示例8: test_read_non_webpage

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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 
开发者ID:anyant,项目名称:rssant,代码行数:11,代码来源:test_reader.py

示例9: _serve_js

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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"
        ) 
开发者ID:tensorflow,项目名称:tensorboard,代码行数:10,代码来源:plugin.py

示例10: _serve_tags

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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") 
开发者ID:tensorflow,项目名称:tensorboard,代码行数:16,代码来源:plugin.py

示例11: test_validate_content_type

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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",
        ) 
开发者ID:tensorflow,项目名称:tensorboard,代码行数:11,代码来源:security_validator_test.py

示例12: upload_complete

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:33,代码来源:__init__.py

示例13: test_response_headers_response

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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') 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:8,代码来源:test_lib_http.py

示例14: render_response

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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) 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:6,代码来源:api.py

示例15: get_data

# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import Response [as 别名]
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 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:15,代码来源:api.py


注:本文中的werkzeug.Response方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。