本文整理汇总了Python中cyclone.web.RequestHandler类的典型用法代码示例。如果您正苦于以下问题:Python RequestHandler类的具体用法?Python RequestHandler怎么用?Python RequestHandler使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RequestHandler类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_error
def write_error(self, error, **kw):
if hasattr(error, 'http_status'):
self.set_status(error.http_status)
self.write({'error_message': error.error_message,
'error_code' : error.error_code})
else:
RequestHandler.write_error(self, error, **kw)
示例2: __init__
def __init__(self, application, request, **kwargs):
RequestHandler.__init__(self, application, request, **kwargs)
self.name = type(self).__name__
self.handler_time_analysis_begin()
self.handler_request_logging_begin()
self.req_id = GLSettings.requests_counter
GLSettings.requests_counter += 1
self.request.start_time = datetime_now()
self.request.request_type = None
if 'import' in self.request.arguments:
self.request.request_type = 'import'
elif 'export' in self.request.arguments:
self.request.request_type = 'export'
language = self.request.headers.get('GL-Language')
if language is None:
for l in self.parse_accept_language_header():
if l in GLSettings.memory_copy.languages_enabled:
language = l
break
if language is None or language not in GLSettings.memory_copy.languages_enabled:
language = GLSettings.memory_copy.default_language
self.request.language = language
self.set_header("Content-Language", language)
示例3: flush
def flush(self, include_footers=False):
"""
This method is used internally by Cyclone,
Cyclone specify the function on_finish but in that time the request is already flushed,
so overwrite flush() was the easiest way to achieve our collection.
It's here implemented to supports the I/O logging if requested
with the command line options --io $number_of_request_recorded
"""
if hasattr(self, 'globaleaks_io_debug'):
try:
content = ("<" * 15)
content += (" Response %d " % self.globaleaks_io_debug)
content += ("<" * 15) + "\n\n"
content += "status code: " + str(self._status_code) + "\n\n"
content += "headers:\n"
for k, v in self._headers.iteritems():
content += "%s: %s\n" % (k, v)
if self._write_buffer is not None:
content += "\nbody: " + str(self._write_buffer) + "\n"
self.do_verbose_log(content)
except Exception as excep:
log.err("JSON logging fail (flush): %s" % excep.message)
return
RequestHandler.flush(self, include_footers)
示例4: write
def write(self, chunk):
"""
This is a monkey patch to RequestHandler to allow us to serialize also
json list objects.
"""
if isinstance(chunk, types.ListType):
self.set_header("Content-Type", "application/json")
chunk = escape.json_encode(chunk)
RequestHandler.write(self, chunk)
示例5: __init__
def __init__(self, application, request, **kwargs):
RequestHandler.__init__(self, application, request, **kwargs)
self.name = type(self).__name__
self.handler_time_analysis_begin()
self.handler_request_logging_begin()
self.req_id = GLSettings.requests_counter
GLSettings.requests_counter += 1
示例6: __init__
def __init__(self, application, request, **kwargs):
RequestHandler.__init__(self, application, request, **kwargs)
self.name = type(self).__name__
self.handler_time_analysis_begin()
self.handler_request_logging_begin()
self.req_id = GLSettings.requests_counter
GLSettings.requests_counter += 1
self.request.language = GLSettings.memory_copy.default_language
self.request.import_export = None
示例7: write_error
def write_error(self, status_code, **kw):
exception = kw.get("exception")
if exception and hasattr(exception, "error_code"):
error_dict = {"error_message": exception.reason, "error_code": exception.error_code}
if hasattr(exception, "arguments"):
error_dict.update({"arguments": exception.arguments})
else:
error_dict.update({"arguments": []})
self.set_status(status_code)
self.finish(error_dict)
else:
RequestHandler.write_error(self, status_code, **kw)
示例8: flush
def flush(self, include_footers=False):
"""
This method is used internally by Cyclone,
Cyclone specify the function on_finish but in that time the request is already flushed,
so overwrite flush() was the easiest way to achieve our collection.
It's here implemented to supports the I/O logging if requested
with the command line options --io $number_of_request_recorded
"""
from globaleaks.event import outcoming_event_monitored, EventTrack
# This is the event tracker, used to keep track of the
# outcome of the events.
if not hasattr(self, '_status_code'):
if GLSetting.devel_mode:
log.debug("Developer, check this out")
import pdb; pdb.set_trace()
else:
raise Exception("Missing _status_code in some place!")
for event in outcoming_event_monitored:
if event['handler_check'](self.request.uri) and \
event['method'] == self.request.method and \
event['status_checker'](self._status_code):
EventTrack(event, self.request.request_time())
# if event['anomaly_management']:
# event['anomaly_management'](self.request)
if hasattr(self, 'globaleaks_io_debug'):
try:
content = ("<" * 15)
content += (" Response %d " % self.globaleaks_io_debug)
content += ("<" * 15) + "\n\n"
content += "status code: " + str(self._status_code) + "\n\n"
content += "headers:\n"
for k, v in self._headers.iteritems():
content += "%s: %s\n" % (k, v)
if self._write_buffer is not None:
content += "\nbody: " + str(self._write_buffer) + "\n"
self.do_verbose_log(content)
except Exception as excep:
log.err("JSON logging fail (flush): %s" % excep.message)
return
RequestHandler.flush(self, include_footers)
示例9: write_error
def write_error(self, status_code, **kw):
exception = kw.get('exception')
if exception and hasattr(exception, 'error_code'):
error_dict = {}
error_dict.update({'error_message': exception.reason, 'error_code': exception.error_code})
if hasattr(exception, 'arguments'):
error_dict.update({'arguments': exception.arguments})
else:
error_dict.update({'arguments': []})
self.set_status(status_code)
self.finish(error_dict)
else:
RequestHandler.write_error(self, status_code, **kw)
示例10: __init__
def __init__(self, application, request, **kwargs):
RequestHandler.__init__(self, application, request, **kwargs)
self.name = type(self).__name__
self.handler_time_analysis_begin()
self.handler_request_logging_begin()
self.req_id = GLSettings.requests_counter
GLSettings.requests_counter += 1
self.request.start_time = datetime_now()
self.request.request_type = None
if 'import' in self.request.arguments:
self.request.request_type = 'import'
elif 'export' in self.request.arguments:
self.request.request_type = 'export'
self.request.language = self.request.headers.get('GL-Language', GLSettings.memory_copy.default_language)
示例11: _handle_request_exception
def _handle_request_exception(self, e):
ret = RequestHandler._handle_request_exception(self, e)
if isinstance(e, Failure):
exc_type, exc_value, exc_tb = [e.type, e.value, e.getTracebackObject()]
e = e.value
else:
exc_type, exc_value, exc_tb = sys.exc_info()
if not isinstance(e, (template.TemplateError,
HTTPError, HTTPAuthenticationRequired)):
mail_exception_handler(exc_type, exc_value, exc_tb)
return ret
示例12: __init__
def __init__(self, application, request, **kwargs):
RequestHandler.__init__(self, application, request, **kwargs)
self.transport = request.connection.transport
self._auto_finish = False
示例13: setUp
def setUp(self):
self.app = Application(some_setting="foo")
self.request = Mock()
self.rh = RequestHandler(self.app, self.request)
示例14: RequestHandlerTest
class RequestHandlerTest(unittest.TestCase):
def assertHasAttr(self, obj, attr_name):
assert hasattr(obj, attr_name)
def setUp(self):
self.app = Application(some_setting="foo")
self.request = Mock()
self.rh = RequestHandler(self.app, self.request)
def test_init(self):
self.assertHasAttr(self.rh, "application")
self.assertHasAttr(self.rh, "request")
self.assertHasAttr(self.rh, "path_args")
self.assertHasAttr(self.rh, "path_kwargs")
self.assertHasAttr(self.rh, "ui")
def test_settings(self):
self.assertEqual(self.rh.settings, {"some_setting": "foo"})
def test_default(self):
self.assertRaises(HTTPError, self.rh.default)
def test_prepare(self):
self.assertEqual(self.rh.prepare(), None)
def test_on_finish(self):
self.assertEqual(self.rh.on_finish(), None)
def test_on_connection_close(self):
self.assertEqual(self.rh.on_connection_close(), None)
def test_clear(self):
self.request.headers = {
"Connection": "Keep-Alive"
}
self.request.supports_http_1_1.return_value = False
self.rh.clear()
self.assertEqual(
set(self.rh._headers.keys()),
{"Server", "Content-Type", "Date", "Connection"},
)
self.assertEqual(self.rh._list_headers, [])
def test_set_status(self):
self.rh.set_status(200)
self.assertEqual(self.rh._status_code, 200)
def test_set_status_with_reason(self):
self.rh.set_status(200, "reason")
self.assertEqual(self.rh._status_code, 200)
self.assertEqual(self.rh._reason, "reason")
def test_set_status_with_invalid_code(self):
self.assertRaises(ValueError, self.rh.set_status, 9999)
def test_get_status(self):
self.rh.set_status(200)
self.assertEqual(self.rh.get_status(), 200)
def test_add_header(self):
self.rh.add_header("X-Header", "something")
self.assertEqual(
self.rh._list_headers,
[("X-Header", "something")]
)
self.rh.add_header("X-Header", "something")
self.assertEqual(
self.rh._list_headers,
[("X-Header", "something"), ("X-Header", "something")]
)
def test_clear_header(self):
self.rh.set_header("X-Header", "something")
self.assertTrue("X-Header" in self.rh._headers)
self.rh.clear_header("X-Header")
self.assertTrue("X-Header" not in self.rh._headers)
def test_convert_header_value(self):
value = self.rh._convert_header_value("Value")
self.assertEqual(value, "Value")
def test_convert_unicode_header_value(self):
value = self.rh._convert_header_value(u"Value")
self.assertEqual(value, "Value")
self.assertTrue(type(value) != unicode_type)
def test_convert_unicode_datetime_header_value(self):
now = datetime(2014, 4, 4)
result = self.rh._convert_header_value(now)
self.assertEqual(
result,
"Fri, 04 Apr 2014 00:00:00 GMT"
)
def test_convert_invalid_value(self):
class Nothing:
pass
self.assertRaises(TypeError, self.rh._convert_header_value, Nothing())
#.........这里部分代码省略.........