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


Python Response.direct_passthrough方法代码示例

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


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

示例1: dbfile_handler

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
    def dbfile_handler(self, environ, args):
        try:
            fobj = self.file_cacher.get_file(args['digest'])
        except KeyError:
            raise NotFound()

        response = Response()
        response.status_code = 200
        response.mimetype = 'application/octet-stream'

        if 'name' in args:
            if args["name"].endswith(".pdf"):
                # Add header to allow the official pdf.js to work
                response.headers.add_header(b'Access-Control-Allow-Origin',
                        b'https://mozilla.github.io')
            else:
                # Don't do this on pdf files because it breaks the native pdf reader
                response.headers.add_header(
                    b'Content-Disposition', b'attachment',
                    filename=args['name'])
            mimetype = mimetypes.guess_type(args['name'])[0]
            if mimetype is not None:
                response.mimetype = mimetype

        response.response = wrap_file(environ, fobj)
        response.direct_passthrough = True
        response.cache_control.max_age = 31536000
        response.cache_control.public = True
        return response
开发者ID:algorithm-ninja,项目名称:cmsocial,代码行数:31,代码来源:pws.py

示例2: _try_special_request

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
    def _try_special_request(self, environ, request):
        static_mount = '/__piecrust_static/'
        if request.path.startswith(static_mount):
            rel_req_path = request.path[len(static_mount):]
            mount = os.path.join(RESOURCES_DIR, 'server')
            full_path = os.path.join(mount, rel_req_path)
            try:
                response = self._make_wrapped_file_response(
                        environ, request, full_path)
                return response
            except OSError:
                pass

        debug_mount = '/__piecrust_debug/'
        if request.path.startswith(debug_mount):
            rel_req_path = request.path[len(debug_mount):]
            if rel_req_path == 'pipeline_status':
                from piecrust.serving.procloop import (
                        PipelineStatusServerSideEventProducer)
                provider = PipelineStatusServerSideEventProducer(
                        self._proc_loop.status_queue)
                it = ClosingIterator(provider.run(), [provider.close])
                response = Response(it)
                response.headers['Cache-Control'] = 'no-cache'
                if 'text/event-stream' in request.accept_mimetypes:
                    response.mimetype = 'text/event-stream'
                response.direct_passthrough = True
                response.implicit_sequence_conversion = False
                return response

        return None
开发者ID:sinistersnare,项目名称:PieCrust2,代码行数:33,代码来源:server.py

示例3: file_handler

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
    def file_handler(self, environ, filename):
        path = os.path.join(pkg_resources.resource_filename("cms.web", "practice"), filename)

        response = Response()
        response.status_code = 200
        response.mimetype = "application/octet-stream"
        mimetype = mimetypes.guess_type(filename)[0]
        if mimetype is not None:
            response.mimetype = mimetype
        response.last_modified = datetime.utcfromtimestamp(os.path.getmtime(path)).replace(microsecond=0)
        response.response = wrap_file(environ, io.open(path, "rb"))
        response.direct_passthrough = True
        return response
开发者ID:veluca93,项目名称:oii-web,代码行数:15,代码来源:PracticeWebServer.py

示例4: wsgi_app

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
    def wsgi_app(self, environ, start_response):
        """Execute this instance as a WSGI application.

        See the PEP for the meaning of parameters. The separation of
        __call__ and wsgi_app eases the insertion of middlewares.

        """
        original_response = Response.from_app(self.wrapped_app, environ)
        # We send relative locations to play nice with reverse proxies
        # but Werkzeug by default turns them into absolute ones.
        original_response.autocorrect_location_header = False

        if self.DIGEST_HEADER not in original_response.headers:
            return original_response

        digest = original_response.headers.pop(self.DIGEST_HEADER)
        filename = original_response.headers.pop(self.FILENAME_HEADER, None)
        mimetype = original_response.mimetype

        try:
            fobj = self.file_cacher.get_file(digest)
            size = self.file_cacher.get_size(digest)
        except KeyError:
            return NotFound()
        except TombstoneError:
            return ServiceUnavailable()

        request = Request(environ)
        request.encoding_errors = "strict"

        response = Response()
        response.status_code = 200
        response.mimetype = mimetype
        if filename is not None:
            response.headers.add(
                "Content-Disposition", "attachment", filename=filename)
        response.set_etag(digest)
        response.cache_control.max_age = SECONDS_IN_A_YEAR
        response.cache_control.private = True
        response.response = \
            wrap_file(environ, fobj, buffer_size=FileCacher.CHUNK_SIZE)
        response.direct_passthrough = True

        try:
            # This takes care of conditional and partial requests.
            response.make_conditional(
                request, accept_ranges=True, complete_length=size)
        except HTTPException as exc:
            return exc

        return response
开发者ID:cms-dev,项目名称:cms,代码行数:53,代码来源:file_middleware.py

示例5: wsgi_app

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
    def wsgi_app(self, environ, start_response):
        request = Request(environ)
        request.encoding_errors = "strict"

        response = Response()
        response.status_code = 200
        response.mimetype = "text/html"
        response.last_modified = \
            datetime.utcfromtimestamp(os.path.getmtime(self.path))\
                    .replace(microsecond=0)
        # TODO check for If-Modified-Since and If-None-Match
        response.response = wrap_file(environ, open(self.path, 'rb'))
        response.direct_passthrough = True

        return response
开发者ID:cms-dev,项目名称:cms,代码行数:17,代码来源:RankingWebServer.py

示例6: test_wrapper_internals

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
def test_wrapper_internals():
    """Test internals of the wrappers"""
    from werkzeug.wrappers import Request
    req = Request.from_values(data={'foo': 'bar'}, method='POST')
    req._load_form_data()
    assert req.form.to_dict() == {'foo': 'bar'}

    # second call does not break
    req._load_form_data()
    assert req.form.to_dict() == {'foo': 'bar'}

    # check reprs
    assert repr(req) == "<Request 'http://localhost/' [POST]>"
    resp = Response()
    assert repr(resp) == '<Response 0 bytes [200 OK]>'
    resp.data = 'Hello World!'
    assert repr(resp) == '<Response 12 bytes [200 OK]>'
    resp.response = iter(['Test'])
    assert repr(resp) == '<Response streamed [200 OK]>'

    # unicode data does not set content length
    response = Response([u'Hällo Wörld'])
    headers = response.get_wsgi_headers(create_environ())
    assert 'Content-Length' not in headers

    response = Response(['Hällo Wörld'])
    headers = response.get_wsgi_headers(create_environ())
    assert 'Content-Length' in headers

    # check for internal warnings
    print 'start'
    filterwarnings('error', category=Warning)
    response = Response()
    environ = create_environ()
    response.response = 'What the...?'
    assert_raises(Warning, lambda: list(response.iter_encoded()))
    assert_raises(Warning, lambda: list(response.get_app_iter(environ)))
    response.direct_passthrough = True
    assert_raises(Warning, lambda: list(response.iter_encoded()))
    assert_raises(Warning, lambda: list(response.get_app_iter(environ)))
    resetwarnings()
开发者ID:EnTeQuAk,项目名称:werkzeug,代码行数:43,代码来源:test_internal.py

示例7: make_wrapped_file_response

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
def make_wrapped_file_response(environ, request, path):
    logger.debug("Serving %s" % path)

    # Check if we can return a 304 status code.
    mtime = os.path.getmtime(path)
    etag_str = '%s$$%s' % (path, mtime)
    etag = hashlib.md5(etag_str.encode('utf8')).hexdigest()
    if etag in request.if_none_match:
        response = Response()
        response.status_code = 304
        return response

    wrapper = wrap_file(environ, open(path, 'rb'))
    response = Response(wrapper)
    _, ext = os.path.splitext(path)
    response.set_etag(etag)
    response.last_modified = datetime.datetime.fromtimestamp(mtime)
    response.mimetype = mimetype_map.get(
            ext.lstrip('.'), 'text/plain')
    response.direct_passthrough = True
    return response
开发者ID:germanschnyder,项目名称:PieCrust2,代码行数:23,代码来源:util.py

示例8: dbfile_handler

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
    def dbfile_handler(self, environ, args):
        try:
            fobj = self.file_cacher.get_file(args['digest'])
        except KeyError:
            raise NotFound()

        response = Response()
        response.status_code = 200

        response.mimetype = 'application/octet-stream'
        if 'filename' in args:
            response.headers.add_header(
                b'Content-Disposition', b'attachment',
                filename=args['filename'])
            mimetype = mimetypes.guess_type(args['filename'])[0]
            if mimetype is not None:
                response.mimetype = mimetype

        response.response = wrap_file(environ, fobj)
        response.direct_passthrough = True
        return response
开发者ID:acube-unipi,项目名称:oii-web,代码行数:23,代码来源:PracticeWebServer.py

示例9: dbfile_handler

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
    def dbfile_handler(self, environ, args):
        try:
            fobj = self.file_cacher.get_file(args["digest"])
        except KeyError:
            raise NotFound()

        response = Response()
        response.status_code = 200
        response.mimetype = "application/octet-stream"

        if "name" in args:
            if not args["name"].endswith(".pdf"):
                # Don't do this on pdf files because it breaks the native pdf reader
                response.headers.add_header(b"Content-Disposition", b"attachment", filename=args["name"])
            mimetype = mimetypes.guess_type(args["name"])[0]
            if mimetype is not None:
                response.mimetype = mimetype

        response.response = wrap_file(environ, fobj)
        response.direct_passthrough = True
        return response
开发者ID:veluca93,项目名称:oii-web,代码行数:23,代码来源:PracticeWebServer.py

示例10: test_wrapper_internals

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
def test_wrapper_internals():
    req = Request.from_values(data={"foo": "bar"}, method="POST")
    req._load_form_data()
    assert req.form.to_dict() == {"foo": "bar"}

    # second call does not break
    req._load_form_data()
    assert req.form.to_dict() == {"foo": "bar"}

    # check reprs
    assert repr(req) == "<Request 'http://localhost/' [POST]>"
    resp = Response()
    assert repr(resp) == "<Response 0 bytes [200 OK]>"
    resp.set_data("Hello World!")
    assert repr(resp) == "<Response 12 bytes [200 OK]>"
    resp.response = iter(["Test"])
    assert repr(resp) == "<Response streamed [200 OK]>"

    # unicode data does not set content length
    response = Response([u"Hällo Wörld"])
    headers = response.get_wsgi_headers(create_environ())
    assert u"Content-Length" not in headers

    response = Response([u"Hällo Wörld".encode("utf-8")])
    headers = response.get_wsgi_headers(create_environ())
    assert u"Content-Length" in headers

    # check for internal warnings
    filterwarnings("error", category=Warning)
    response = Response()
    environ = create_environ()
    response.response = "What the...?"
    pytest.raises(Warning, lambda: list(response.iter_encoded()))
    pytest.raises(Warning, lambda: list(response.get_app_iter(environ)))
    response.direct_passthrough = True
    pytest.raises(Warning, lambda: list(response.iter_encoded()))
    pytest.raises(Warning, lambda: list(response.get_app_iter(environ)))
    resetwarnings()
开发者ID:pallets,项目名称:werkzeug,代码行数:40,代码来源:test_internal.py

示例11: wsgi_app

# 需要导入模块: from werkzeug.wrappers import Response [as 别名]
# 或者: from werkzeug.wrappers.Response import direct_passthrough [as 别名]
    def wsgi_app(self, environ, start_response):
        route = self.router.bind_to_environ(environ)
        try:
            endpoint, args = route.match()
        except HTTPException as exc:
            return exc

        location = self.location % args

        request = Request(environ)
        request.encoding_errors = "strict"

        response = Response()

        available = list()
        for extension, mimetype in self.EXT_TO_MIME.iteritems():
            if os.path.isfile(location + '.' + extension):
                available.append(mimetype)
        mimetype = request.accept_mimetypes.best_match(available)
        if mimetype is not None:
            path = "%s.%s" % (location, self.MIME_TO_EXT[mimetype])
        else:
            path = self.fallback
            mimetype = 'image/png'  # FIXME Hardcoded type.

        response.status_code = 200
        response.mimetype = mimetype
        response.last_modified = \
            datetime.utcfromtimestamp(os.path.getmtime(path))\
                    .replace(microsecond=0)

        # TODO check for If-Modified-Since and If-None-Match

        response.response = wrap_file(environ, io.open(path, 'rb'))
        response.direct_passthrough = True

        return response
开发者ID:Corea,项目名称:cms,代码行数:39,代码来源:RankingWebServer.py


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