本文整理汇总了Python中asyncio.Future类的典型用法代码示例。如果您正苦于以下问题:Python Future类的具体用法?Python Future怎么用?Python Future使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Future类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_tls
def start_tls(self, server_side, ssl_options=None, server_hostname=None, connect_timeout=None):
if not self._transport or self._read_future:
raise ValueError("IOStream is not idle; cannot convert to SSL")
self._connect_ssl_future = connect_ssl_future = Future(loop=self._loop)
waiter = Future(loop=self._loop)
def on_connected(future):
if self._loop_connect_timeout:
self._loop_connect_timeout.cancel()
self._loop_connect_timeout = None
if connect_ssl_future._exception is not None:
self.on_closed(future.exception())
self._connect_ssl_future = None
else:
self._connect_ssl_future = None
connect_ssl_future.set_result(self)
waiter.add_done_callback(on_connected)
if connect_timeout:
def on_timeout():
self._loop_connect_timeout = None
if not waiter.done():
self.close((None, IOError("Connect timeout"), None))
self._loop_connect_timeout = self._loop.call_later(connect_timeout, on_timeout)
self._transport.pause_reading()
sock, self._transport._sock = self._transport._sock, None
self._transport = self._loop._make_ssl_transport(
sock, self, ssl_options, waiter,
server_side=False, server_hostname=server_hostname)
return connect_ssl_future
示例2: filter_stderr
def filter_stderr(popen:subprocess.Popen, future:asyncio.Future):
last_ex = None
while True:
data = popen.stderr.readline()
if data:
log.ffmpeg("Data from ffmpeg: {}".format(data))
try:
if check_stderr(data):
sys.stderr.buffer.write(data)
sys.stderr.buffer.flush()
except FFmpegError as e:
log.ffmpeg("Error from ffmpeg: %s", str(e).strip())
last_ex = e
except FFmpegWarning:
pass # useless message
else:
break
if last_ex:
future.set_exception(last_ex)
else:
future.set_result(True)
示例3: filter_stderr
def filter_stderr(popen:subprocess.Popen, future:asyncio.Future):
last_ex = None
while True:
data = popen.stderr.readline()
if data:
# print("FFmpeg says:", data, flush=True)
try:
if check_stderr(data):
sys.stderr.buffer.write(data)
sys.stderr.buffer.flush()
except FFmpegError as e:
print("Error from FFmpeg:", e)
last_ex = e
except FFmpegWarning:
pass # useless message
else:
break
if last_ex:
future.set_exception(last_ex)
else:
future.set_result(True)
示例4: __init__
class Tester:
def __init__(self):
self.end = Future()
def __call__(self, *args, **kwargs):
if not self.end.done():
self.end.set_result((args, kwargs))
示例5: side_effect
def side_effect(*args, **kwargs):
def _side_effect(*args, **kwargs):
fut = Future()
fut.set_result({'origin': '127.0.0.1'})
return fut
resp = Mock()
resp.json.side_effect = resp.release.side_effect = _side_effect
fut = Future()
fut.set_result(resp)
return fut
示例6: test_json_with_async_string2
def test_json_with_async_string2(self):
d = Future()
astr = wsgi.AsyncString(d)
response = wsgi.Json({'bla': astr})
self.assertEqual(len(response.children), 1)
result = response.render()
self.assertIsInstance(result, Future)
d.set_result('ciao')
result = yield result
self.assertEqual(result, json.dumps({'bla': 'ciao'}))
示例7: js_query
def js_query(self, query) -> Future:
if self.connected:
self.js_exec(query, self._reqid)
fut = Future()
self._tasks[self._reqid] = fut
self._reqid += 1
return fut
else:
fut = Future()
fut.set_result(None)
return fut
示例8: wait_for_fd
def wait_for_fd(fd, *, loop=None):
"""Given a file descriptor, block on it until we have input to read"""
if hasattr(fd, 'fileno'):
fd = fd.fileno()
if not loop:
loop = get_event_loop()
waiter = Future(loop=loop)
loop.add_reader(fd, lambda : waiter.set_result(None))
yield from waiter
loop.remove_reader(fd)
示例9: CustomWSClientProtocol
class CustomWSClientProtocol(WebSocketClientProtocol):
"""Add auto-ping switch (dirty way) and let us start handshaking manually."""
# this framework mix camel and underline naming style, nice!
def __init__(self):
WebSocketClientProtocol.__init__(self)
self.customUriPath = '/'
self.customWsKey = None
self._delayedHandshake = Future()
def setAutoPing(self, interval, timeout):
"""Set auto-ping interval. Start it if it's not running."""
self.disableAutoPing()
self.autoPingInterval = interval
self.autoPingTimeout = timeout
self.autoPingPendingCall = loop.call_later(interval, self._sendAutoPing)
def disableAutoPing(self):
if self.autoPingPendingCall:
self.autoPingPendingCall.cancel()
self.autoPingPendingCall = None
def startHandshake(self):
"""Delay handshake because some states must be set right before handshake (so
they can't be set in factory)."""
self._delayedHandshake.set_result(None)
@coroutine
def restartHandshake(self):
"""Resume delayed handshake. It enable us to customize handshake HTTP header."""
yield from wait_for(self._delayedHandshake, None)
if config.compatible:
self.websocket_key = base64.b64encode(os.urandom(16))
else:
self.websocket_key = self.customWsKey
request = [
'GET %s HTTP/1.1' % self.customUriPath,
'Host: %s:%d' % (self.factory.host, self.factory.port),
'Sec-WebSocket-Key: %s' % self.websocket_key.decode(),
'Sec-WebSocket-Version: %d' % self.SPEC_TO_PROTOCOL_VERSION[self.version],
'Pragma: no-cache',
'Cache-Control: no-cache',
'Connection: Upgrade',
'Upgrade: WebSocket',
]
if config.compatible:
# store custom ws key in cookie to prevent it from being changed by ws proxy
request.append('Cookie: %s=%s' % (config.cookie_key, self.customWsKey.decode()))
if self.factory.useragent:
request.append('User-Agent: %s' % self.factory.useragent)
self.http_request_data = '\r\n'.join(request).encode('utf8') + b'\r\n\r\n'
self.sendData(self.http_request_data)
if self.debug:
self.log.debug(request)
示例10: test_run_coroutine_job
async def test_run_coroutine_job(asyncio_scheduler, asyncio_executor, exception):
from asyncio import Future, sleep
future = Future()
job = asyncio_scheduler.add_job(waiter, 'interval', seconds=1, args=[sleep, exception])
asyncio_executor._run_job_success = lambda job_id, events: future.set_result(events)
asyncio_executor._run_job_error = lambda job_id, exc, tb: future.set_exception(exc)
asyncio_executor.submit_job(job, [datetime.now(utc)])
events = await future
assert len(events) == 1
if exception:
assert str(events[0].exception) == 'dummy error'
else:
assert events[0].retval is True
示例11: go
def go():
future = Future()
future.set_result(42)
source = Observable.from_future(future)
def on_next(x):
success[0] = 42 == x
def on_error(err):
success[1] = False
def on_completed():
success[2] = True
subscription = source.subscribe(on_next, on_error, on_completed)
示例12: __init__
def __init__(self, title='', label_text='', completer=None):
self.future = Future()
def accept_text(buf):
get_app().layout.focus(ok_button)
buf.complete_state = None
return True
def accept():
self.future.set_result(self.text_area.text)
def cancel():
self.future.set_result(None)
self.text_area = TextArea(
completer=completer,
multiline=False,
width=D(preferred=40),
accept_handler=accept_text)
ok_button = Button(text='OK', handler=accept)
cancel_button = Button(text='Cancel', handler=cancel)
self.dialog = Dialog(
title=title,
body=HSplit([
Label(text=label_text),
self.text_area
]),
buttons=[ok_button, cancel_button],
width=D(preferred=80),
modal=True)
示例13: _on_reply
def _on_reply(self, action, name, on_reply_ok, on_reply_error):
def callback(future):
reply = future.result()
if query['id'] == reply['id'] and reply['status'] == 'ok':
on_reply_ok(reply)
elif query['id'] == reply['id']:
on_reply_error(reply['reason'].capitalize() + '.')
else:
raise Exception()
query = {'id': uuid4().hex, 'command': action}
query['properties'] = {'name': name}
if action == 'incr' or action == 'decr':
query['properties'].update({'waiting': False, 'nb': 1})
elif action == 'start' or action == 'stop':
query['properties'].update({'waiting': False, 'match': 'glob'})
# Block to prevent writing multiple requests before reading a reply.
if self._rep2:
yield from self._rep2
self._rep2 = Future()
self._rep2.add_done_callback(callback)
self._req2.write([dumps(query).encode()])
示例14: go
def go():
future = Future()
future.set_result(42)
source = rx.from_future(future)
def on_next(x):
success[0] = x == 42
def on_error(err):
success[1] = False
def on_completed():
success[2] = True
source.subscribe(on_next, on_error, on_completed)
示例15: _send_request
def _send_request(self, app_name, endpoint, entity, params):
packet = MessagePacket.request(self.name, self.version, app_name, _Service._REQ_PKT_STR, endpoint, params,
entity)
future = Future()
request_id = params['request_id']
self._pending_requests[request_id] = future
try:
self.tcp_bus.send(packet)
except ClientException as e:
if not future.done() and not future.cancelled():
ERROR = '101_Client not found'
exception = RequestException(ERROR)
exception.error = ERROR
future.set_exception(exception)
_Service.time_future(future, TCPServiceClient.REQUEST_TIMEOUT_SECS)
return future