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


Python Response.encode_content方法代码示例

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


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

示例1: setUp

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import encode_content [as 别名]
    def setUp(self):
        super(Test_Fix_Content_Encoding, self).setUp()

        self.response_data = '{"test": "json"}'

        response = Response()
        response.body = self.response_data
        response.encode_content(encoding='gzip')
        self.response_data_gzipped = response.body
开发者ID:BryanSD,项目名称:curryproxy,代码行数:11,代码来源:test__fix_content_encoding.py

示例2: create_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import encode_content [as 别名]
def create_response(content_dicts=[]):
	res = Response()
	# add more properties to header
	res.headerlist.append( ('Connection', 'Keep-Alive') )
	res.headerlist.append( ('Keep-Alive', 'timeout=5, max=96') )

	# set json and encode content
	res.json = content_dicts
	res.encode_content()

	return res
开发者ID:krittameth-teacha,项目名称:pcms_collections,代码行数:13,代码来源:mt_tcp_server.py

示例3: test_encode_content_gzip_notyet_gzipped_lazy

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import encode_content [as 别名]
def test_encode_content_gzip_notyet_gzipped_lazy():
    res = Response()
    res.app_iter = StringIO('foo')
    result = res.encode_content('gzip', lazy=True)
    eq_(result, None)
    eq_(res.content_length, None)
    eq_(list(res.app_iter), ['\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff', '',
                             'K\xcb\xcf\x07\x00', '!es\x8c\x03\x00\x00\x00'])
开发者ID:GdZ,项目名称:scriptfile,代码行数:10,代码来源:test_response.py

示例4: application

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import encode_content [as 别名]
def application(req):
    #make sure that we are getting clean data from the user
    values = {}
    for strField in ["type", "machine", "branch", "test", "graphby",
                     "extradata", "setids", "action"]:
        val = req.params.get(strField)
        if strField == "test":
            strField = "testname"
        if not checkString(val):
            raise exc.HTTPBadRequest("Invalid string arg: %r" % strField)
        values[strField] = val

    for numField in ["setid", "raw", "starttime", "endtime", "datelimit", "getlist", "date"]:
        val = req.params.get(numField)
        if not checkNumber(val):
            raise exc.HTTPBadRequest("Invalid string arg %s: %r" % (numField, val))
        values[numField] = val

    values.setdefault('datelimit', 0)
    action = values['action']

    resp = Response()

    if action == 'testinfo':
        doTestInfo(resp, values['setid'])
    elif action == 'finddiscretetestid':
        doFindDiscreteTest(resp, values['testname'], values['date'], values['machine'])
    elif action == 'findcontinuoustestid':
        doFindContinuousTest(resp, values['testname'], values['machine'], values['branch'])
    elif not values.get('setid') and not values.get('getlist') and not values.get('setids'):
        doListTests(resp, values['type'], values['datelimit'], values['branch'], values['machine'], values['testname'], values['graphby'])
    elif values.get('setids') and not values.get('getlist'):
        doSendAllResults(resp, values['setids'])
    elif not values.get('getlist'):
        doSendResults(resp, values['setid'], values['starttime'], values['endtime'], values['raw'], values['graphby'], values['extradata'])
    else:
        doGetList(resp, values['type'], values['branch'], values['machine'], values['testname'])

    resp.headers['Access-Control-Allow-Origin'] = '*'
    resp.content_type = 'text/plain'
    if 'gzip' in resp.accept_encoding:
        resp.encode_content('gzip')

    return resp
开发者ID:jfsiii,项目名称:graphs,代码行数:46,代码来源:getdata_cgi.py

示例5: test_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import encode_content [as 别名]
def test_response():
    req = BaseRequest.blank('/')
    res = req.get_response(simple_app)
    assert res.status == '200 OK'
    assert res.status_int == 200
    assert res.body == "OK"
    assert res.charset == 'utf8'
    assert res.content_type == 'text/html'
    res.status = 404
    assert res.status == '404 Not Found'
    assert res.status_int == 404
    res.body = 'Not OK'
    assert ''.join(res.app_iter) == 'Not OK'
    res.charset = 'iso8859-1'
    assert res.headers['content-type'] == 'text/html; charset=iso8859-1'
    res.content_type = 'text/xml'
    assert res.headers['content-type'] == 'text/xml; charset=iso8859-1'
    res.headers = {'content-type': 'text/html'}
    assert res.headers['content-type'] == 'text/html'
    assert res.headerlist == [('content-type', 'text/html')]
    res.set_cookie('x', 'y')
    assert res.headers['set-cookie'].strip(';') == 'x=y; Path=/'
    res = Response('a body', '200 OK', content_type='text/html')
    res.encode_content()
    assert res.content_encoding == 'gzip'
    eq_(res.body, '\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xffKTH\xcaO\xa9\x04\x00\xf6\x86GI\x06\x00\x00\x00')
    res.decode_content()
    assert res.content_encoding is None
    assert res.body == 'a body'
    res.set_cookie('x', u'foo') # test unicode value
    assert_raises(TypeError, Response, app_iter=iter(['a']),
                  body="somebody")
    del req.environ
    eq_(Response(request=req)._environ, req)
    eq_(Response(request=req)._request, None)
    assert_raises(TypeError, Response, charset=None,
                  body=u"unicode body")
    assert_raises(TypeError, Response, wrong_key='dummy')
开发者ID:GdZ,项目名称:scriptfile,代码行数:40,代码来源:test_response.py

示例6: ResponseBase

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import encode_content [as 别名]
class ResponseBase(object):
    """Base class for responses.

    Attributes:
        response: A webob.Response to be returned to the client.

    """
    def __init__(self, request):
        """Initializes a basic response.

        Each response keeps an internal record of its initiating request with
        this base constructor. An empty webob.Response to be returned to the
        client is also created here (in most cases, the response will be
        modified after its creation here before being returned to the client).

        Args:
            request: webob.Request representation of the incoming request.

        """
        self._request = request
        self._response = Response()

    def _aggregate_response_bodies(self):
        """Aggregates multiple responses into one summarizing JSON response.

        Creates a "meta-response" containing information about all responses
        received from destination endpoints. If a connection to a destination
        endpoint fails, a None entry will appear. Otherwise, each entry will
        contain the destination URL, HTTP status & reason, headers, and body.

        Returns:
            A "meta-response" containing information about all responses
            received from destination endpoints.

        """
        results = []
        for response in self._responses:
            if response is None:
                results.append(None)
                continue

            result = {}
            result['url'] = response.url
            result['status'] = '{0} {1}'.format(response.status_code,
                                                response.reason)
            result['headers'] = dict(response.headers)
            result['body'] = response.content

            results.append(result)

        self._response.body = json.dumps(results)
        self._response.content_type = 'application/json'

    def _fix_headers(self):
        """Adjusts the Content-Encoding and Date headers if needed."""
        self._fix_content_encoding()
        self._fix_date()

    def _fix_content_encoding(self):
        """Adjusts the Content-Encoding header if needed.

        Ensures the Content-Encoding of the response will be accepted by the
        original requestor. CurryProxy automatically attempts to use gzip
        encoding when communicating with destination endpoints even if the
        original client doesn't support gzip. Likewise, a response from a
        destination endpoint may not be gzip-encoded even if a requestor were
        to support the encoding. As such, we must either encode or decode the
        response to the original requestor depending on what it supports and on
        what the destination endpoints returned.

        """
        # Add gzip encoding if the client supports it
        if (self._response.content_encoding is None
                or 'gzip' not in self._response.content_encoding
                and self._request.accept_encoding
                and 'gzip' in self._request.accept_encoding):
            self._response.encode_content(encoding='gzip')

        # Remove gzip encoding if the client doesn't support it
        if (self._request.accept_encoding is None
                or self._response.content_encoding
                and 'gzip' in self._response.content_encoding
                and 'gzip' not in self._request.accept_encoding):
            self._response.decode_content()

    def _fix_date(self):
        """Adjusts the Date header.

        Since CurryProxy is modifying responses in some cases, modify the Date
        header to reflect the time the response was created.

        """
        self._response.date = datetime.utcnow()

    @property
    def response(self):
        """A webob.Response to be returned to the client."""
        return self._response
开发者ID:BryanSD,项目名称:curryproxy,代码行数:100,代码来源:response_base.py

示例7: test_encode_content_gzip_already_gzipped

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import encode_content [as 别名]
def test_encode_content_gzip_already_gzipped():
    res = Response()
    res.content_encoding = 'gzip'
    result = res.encode_content('gzip')
    eq_(result, None)
开发者ID:GdZ,项目名称:scriptfile,代码行数:7,代码来源:test_response.py

示例8: test_encode_content_identity

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import encode_content [as 别名]
def test_encode_content_identity():
    res = Response()
    result = res.encode_content('identity')
    eq_(result, None)
开发者ID:GdZ,项目名称:scriptfile,代码行数:6,代码来源:test_response.py

示例9: gzip_server

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import encode_content [as 别名]
def gzip_server(environ, start_response):
    response = Response("this is some text that will be compressed")
    response.encode_content(encoding="gzip")
    return response(environ, start_response)
开发者ID:imdeany,项目名称:webobtoolkit,代码行数:6,代码来源:test_quickstart.py


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