本文整理汇总了Python中tornado.concurrent.Future.set_exception方法的典型用法代码示例。如果您正苦于以下问题:Python Future.set_exception方法的具体用法?Python Future.set_exception怎么用?Python Future.set_exception使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.concurrent.Future
的用法示例。
在下文中一共展示了Future.set_exception方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: apply
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def apply(callback) -> 'promise.Promise':
f = Future()
try:
f.set_result(callback())
except BaseException as e:
f.set_exception(e)
return Promise(f)
示例2: _start_processing_requests
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def _start_processing_requests(self):
while True:
data = yield gen.Task(self._stream.read_until, '\r\n')
log.debug('New request: %r', data)
try:
msg = json.loads(data)
key = msg['key']
method = msg['method']
args = msg['args']
kwargs = msg['kwargs']
except (KeyError, ValueError):
log.error('Malformed request data: %s', data)
continue
try:
res = self._handler(method, *args, **kwargs)
if isinstance(res, Future):
future = res
else:
future = Future()
future.set_result(res)
except Exception as e:
log.exception('Failed to handle request: %s', key)
future = concurrent.TracebackFuture()
future.set_exception(e)
future.add_done_callback(partial(self._on_future_finished, key))
示例3: _create_stream
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def _create_stream(self, max_buffer_size, af, addr, source_ip=None,
source_port=None):
# Always connect in plaintext; we'll convert to ssl if necessary
# after one connection has completed.
source_port_bind = source_port if isinstance(source_port, int) else 0
source_ip_bind = source_ip
if source_port_bind and not source_ip:
# User required a specific port, but did not specify
# a certain source IP, will bind to the default loopback.
source_ip_bind = '::1' if af == socket.AF_INET6 else '127.0.0.1'
# Trying to use the same address family as the requested af socket:
# - 127.0.0.1 for IPv4
# - ::1 for IPv6
socket_obj = socket.socket(af)
set_close_exec(socket_obj.fileno())
if source_port_bind or source_ip_bind:
# If the user requires binding also to a specific IP/port.
try:
socket_obj.bind((source_ip_bind, source_port_bind))
except socket.error:
socket_obj.close()
# Fail loudly if unable to use the IP/port.
raise
try:
stream = IOStream(socket_obj,
max_buffer_size=max_buffer_size)
except socket.error as e:
fu = Future()
fu.set_exception(e)
return fu
else:
return stream, stream.connect(addr)
示例4: open
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def open(self):
try:
future = self._stream.open()
except Exception as e:
future = Future()
future.set_exception(e)
return future
示例5: ManualCapClient
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
class ManualCapClient(BaseCapClient):
def capitalize(self, request_data, callback=None):
logging.debug("capitalize")
self.request_data = request_data
self.stream = IOStream(socket.socket())
self.stream.connect(('127.0.0.1', self.port),
callback=self.handle_connect)
self.future = Future()
if callback is not None:
self.future.add_done_callback(
stack_context.wrap(lambda future: callback(future.result())))
return self.future
def handle_connect(self):
logging.debug("handle_connect")
self.stream.write(utf8(self.request_data + "\n"))
self.stream.read_until(b'\n', callback=self.handle_read)
def handle_read(self, data):
logging.debug("handle_read")
self.stream.close()
try:
self.future.set_result(self.process_response(data))
except CapError as e:
self.future.set_exception(e)
示例6: run
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def run(child_gr, *args, **kwargs):
try:
result = func(*args, **kwargs)
if not is_future(result):
return child_gr.switch(result)
except Exception as e:
result = Future()
result.set_exception(e)
return ioloop.add_future(result, child_gr.switch)
示例7: side_effect
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def side_effect(request, **kwargs):
if request is not HTTPRequest:
request = HTTPRequest(request)
buffer = StringIO(body)
response = HTTPResponse(request, status_code, buffer=buffer)
future = Future()
if response.error:
future.set_exception(response.error)
else:
future.set_result(response)
return future
示例8: test_non_successful_responses_marks_client_as_failed
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def test_non_successful_responses_marks_client_as_failed(self):
client = self.get_app().sentry_client
with patch.object(client, "_failed_send") as mock_failed:
with patch.object(client, "_send_remote") as mock_send:
f = Future()
f.set_exception(HTTPError(499, "error"))
mock_send.return_value = f
client.send()
yield gen.sleep(0.01) # we need to run after the async send
assert mock_failed.called
示例9: _create_stream
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def _create_stream(self, max_buffer_size, af, addr):
# Always connect in plaintext; we'll convert to ssl if necessary
# after one connection has completed.
try:
stream = IOStream(socket.socket(af),
io_loop=self.io_loop,
max_buffer_size=max_buffer_size)
except socket.error as e:
fu = Future()
fu.set_exception(e)
return fu
else:
return stream.connect(addr)
示例10: _build_response
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def _build_response(self, tid):
"""
Prepare for a response, returns a future
:param tid:
:return: Future
"""
f = Future()
if not self._connected:
f.set_exception(ConnectionException("Client is not connected"))
return f
self.transaction.addTransaction(f, tid)
return f
示例11: with_timeout
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def with_timeout(timeout, future, io_loop=None):
"""Wraps a `.Future` in a timeout.
Raises `TimeoutError` if the input future does not complete before
``timeout``, which may be specified in any form allowed by
`.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
relative to `.IOLoop.time`)
Currently only supports Futures, not other `YieldPoint` classes.
.. versionadded:: 4.0
"""
# TODO: allow yield points in addition to futures?
# Tricky to do with stack_context semantics.
#
# It's tempting to optimize this by cancelling the input future on timeout
# instead of creating a new one, but A) we can't know if we are the only
# one waiting on the input future, so cancelling it might disrupt other
# callers and B) concurrent futures can only be cancelled while they are
# in the queue, so cancellation cannot reliably bound our waiting time.
result = Future()
chain_future(future, result)
if io_loop is None:
io_loop = IOLoop.current()
timeout_handle = io_loop.add_timeout(timeout, lambda: result.set_exception(TimeoutError("Timeout")))
if isinstance(future, Future):
# We know this future will resolve on the IOLoop, so we don't
# need the extra thread-safety of IOLoop.add_future (and we also
# don't care about StackContext here.
future.add_done_callback(lambda future: io_loop.remove_timeout(timeout_handle))
else:
# concurrent.futures.Futures may resolve on any thread, so we
# need to route them back to the IOLoop.
io_loop.add_future(future, lambda future: io_loop.remove_timeout(timeout_handle))
return result
示例12: test_fails_before_timeout
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def test_fails_before_timeout(self):
future = Future()
self.io_loop.add_timeout(
datetime.timedelta(seconds=0.1),
lambda: future.set_exception(ZeroDivisionError))
with self.assertRaises(ZeroDivisionError):
yield gen.with_timeout(datetime.timedelta(seconds=3600), future)
示例13: test_unsuccessful_future
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def test_unsuccessful_future(self):
class BadFuture(Exception):
pass
future = Future()
def run():
with self.assertRaises(BadFuture):
utils.run_async(future)
self.stop()
gr = greenlet.greenlet(run)
gr.switch()
future.set_exception(BadFuture("you have been exterminated"))
self.wait()
示例14: open
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def open(self):
if self._unix_socket:
address = self._unix_socket
else:
address = (self._host, self._port)
try:
future = self.connect(address)
if self._timeout > 0:
def timeout():
if self._connecting:
self.close((None, TStreamConnectTimeoutError(), None))
self.io_loop.add_timeout(time.time() + self._timeout, timeout)
except Exception as e:
future = Future()
future.set_exception(e)
return future
示例15: GuarantedHTTPRequest
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
class GuarantedHTTPRequest(HTTPRequest):
def __init__(self, *args, **kwargs):
self._first_chunk_recieved = False
self.timeout_handle = None
self._io_loop = ioloop.IOLoop.current()
if "streaming_callback" in kwargs:
self.orig_streaming_callback = kwargs["streaming_callback"]
else:
self.orig_streaming_callback = None
if "inactive_timeout" in kwargs:
self.inactive_timeout = kwargs["inactive_timeout"]
else:
self.inactive_timeout = 1
del kwargs["inactive_timeout"]
self.timeout_future = Future()
kwargs["streaming_callback"] = self.stream_cb
super(GuarantedHTTPRequest, self).__init__(*args, **kwargs)
def stream_cb(self, data):
self._first_chunk_recieved = True
if self.orig_streaming_callback:
self.orig_streaming_callback(data)
io_loop = self._io_loop
if self.timeout_handle:
io_loop.remove_timeout(self.timeout_handle)
self.timeout_handle = io_loop.call_at(io_loop.time()+1,
self.throwStreamingTimeout)
def throwStreamingTimeout(self):
err = HTTPError(
504,
message="No activity from server for {} second(s)".format(
self.inactive_timeout))
self.timeout_future.set_exception(err)
def done(self):
if self._first_chunk_recieved:
io_loop = self._io_loop
io_loop.remove_timeout(self.timeout_handle)