本文整理汇总了Python中webob.Response.decode_content方法的典型用法代码示例。如果您正苦于以下问题:Python Response.decode_content方法的具体用法?Python Response.decode_content怎么用?Python Response.decode_content使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webob.Response
的用法示例。
在下文中一共展示了Response.decode_content方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_decode_content_with_deflate
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import decode_content [as 别名]
def test_decode_content_with_deflate():
res = Response()
b = 'Hey Hey Hey'
# Simulate inflate by chopping the headers off
# the gzip encoded data
res.body = zlib.compress(b)[2:-4]
res.content_encoding = 'deflate'
res.decode_content()
eq_(res.body, b)
eq_(res.content_encoding, None)
示例2: test_decode_content_gzip
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import decode_content [as 别名]
def test_decode_content_gzip():
from gzip import GzipFile
io = StringIO()
gzip_f = GzipFile(filename='', mode='w', fileobj=io)
gzip_f.write('abc')
gzip_f.close()
body = io.getvalue()
res = Response()
res.content_encoding = 'gzip'
res.body = body
res.decode_content()
eq_(res.body, 'abc')
示例3: test_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import decode_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')
示例4: WebController
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import decode_content [as 别名]
#.........这里部分代码省略.........
return self._session_key
def delete_cookie(self, key):
self.__response.delete_cookie(key)
def set_cookie(self, key):
value = self.new_session
self.__response.set_cookie(key, bytes(value))
return value
def process(self, environ, start_response):
self._begin = datetime.datetime.now()
if self._debug:
open("/tmp/cog_sql", "w")
try:
self.clear()
self._environ = environ
# open("/tmp/cog_tmp_xxx", "w").write("{}".format(environ))
self._script_name = self._environ.get('SCRIPT_NAME', '')
self._server_name = self._environ['HTTP_HOST']
self._url_scheme = self._environ['wsgi.url_scheme']
self._url = "{}://{}{}".format(
self._url_scheme, self._server_name, self._script_name)
self._path_info = self._environ['PATH_INFO'].lower()
alnum = "[a-z0-9]{4}"
oid_pattern = '^/{}{}-{}-{}-{}-{}{}{}$'.format(*(alnum,)*8)
if re.match(oid_pattern, self._path_info):
obj = self.db.get_elt_by_oid(self._path_info[1:])
self.add_json_res({'#page_ref':self.get_page_ref()})
self.direct_obj_ref = obj.w3display
self.load_site()
self.__request = Request(environ)
self.__lang = Accept(str(self.__request.accept_language))
self.i18n = gettext.translation(
'messages', '/usr/share/collorg/locale',
[self.__lang.best_match(('en', 'fr', 'fr-FR')) or 'en'])
if WebController.__static_body is None:
WebController.__tags = self.__get_tags()
WebController.__static_body = self.__get_static_body()
self.__response = Response()
self.__reset()
if not(self._cog_method is None and '#page_ref' in self._json_res):
self.add_json_res({'#page_ref':self.get_page_ref()})
self.__response.unicode_body = self._unicode(self.__exec())
if(self.__response.content_type != 'text/html' or
self.__response.status_int != 200):
# Not an HTML response, we don't want to
# do anything to it
return self.__response(environ, start_response)
# Make sure the content isn't gzipped:
self.__response.decode_content()
return self.__response(environ, start_response)
except Exception as err:
if self.db._cog_params['debug']:
response = Response()
response.unicode_body = self._unicode(err)
return response(environ, start_response)
if raise_error:
raise err
def debug(self, error = None):
output = []
css_style = 'debug hidden toggle'
css_error = ''
if error:
css_style += ' debug_error'
css_error = 'debug_error'
title = error and "Error" or "debug"
link = ( '<span class="link toggle %s" '
'to_toggle="#cog_debug">%s</span>' % (css_error, title))
if error:
output.append('<h2>Error</h2>')
output.append('<pre>%s</pre>' % (self.__pfce(error)))
output.append("<h2>Traceback</h2>")
output.append("<pre>%s</pre>"%(
traceback.format_exc()))
output.append('<h2>Main variables</h2>')
output.append('<pre>')
output.append('cog_method = %s\n' % (self._cog_method))
output.append('cog_fqtn_ = %s\n' % (self._cog_fqtn_))
output.append('cog_oid_ = %s\n' % (self._cog_oid_))
output.append('cog_ref_oid = %s\n' % (self._cog_ref_oid))
output.append('</pre>')
if error:
post_error = self.db.table(
'collorg.application.communication.error')
try:
post_error.hit(
self._cog_fqtn_, self._cog_method, traceback.format_exc())
except Exception, err:
sys.stderr.write("Warning! {}\n".format(err))
# open("/tmp/cog_error_log", "a+").write("{}\n".format(err))
output.append('<h2>Query string</h2>')
output.append('<pre>qs = %s</pre>' % (self.__pfce(self.__get_request)))
output.append('<h2>Command executed</h2>')
output.append('<pre>cmd = %s</pre>' %(self.__pfce(self._cog_cmd)))
output.append('<h2>Environ</h2>')
output.append('<pre>%s</pre>' % (self.__pfce(self._environ)))
u_output = [self._unicode(elt) for elt in output]
return link, "\n".join(u_output)
示例5: ResponseBase
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import decode_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
示例6: test_decode_content_identity
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import decode_content [as 别名]
def test_decode_content_identity():
res = Response()
res.content_encoding = 'identity'
result = res.decode_content()
eq_(result, None)
示例7: test_decode_content_defaults_to_identity
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import decode_content [as 别名]
def test_decode_content_defaults_to_identity():
res = Response()
res.body = 'There be dragons'
res.decode_content()
eq_(res.body, 'There be dragons')