本文整理汇总了Python中tornado.gen.with_timeout方法的典型用法代码示例。如果您正苦于以下问题:Python gen.with_timeout方法的具体用法?Python gen.with_timeout怎么用?Python gen.with_timeout使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.gen
的用法示例。
在下文中一共展示了gen.with_timeout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: open
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def open(self, timeout=None):
logger.debug('socket connecting')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
self.stream = iostream.IOStream(sock)
try:
connect = self.stream.connect((self.host, self.port))
if timeout is not None:
yield self.with_timeout(timeout, connect)
else:
yield connect
except (socket.error, IOError, ioloop.TimeoutError) as e:
message = 'could not connect to {}:{} ({})'.format(self.host, self.port, e)
raise TTransportException(
type=TTransportException.NOT_OPEN,
message=message)
raise gen.Return(self)
示例2: wait
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]:
"""Block until the internal flag is true.
Returns an awaitable, which raises `tornado.util.TimeoutError` after a
timeout.
"""
fut = Future() # type: Future[None]
if self._value:
fut.set_result(None)
return fut
self._waiters.add(fut)
fut.add_done_callback(lambda fut: self._waiters.remove(fut))
if timeout is None:
return fut
else:
timeout_fut = gen.with_timeout(
timeout, fut, quiet_exceptions=(CancelledError,)
)
# This is a slightly clumsy workaround for the fact that
# gen.with_timeout doesn't cancel its futures. Cancelling
# fut will remove it from the waiters list.
timeout_fut.add_done_callback(
lambda tf: fut.cancel() if not fut.done() else None
)
return timeout_fut
示例3: test_gc
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def test_gc(self):
# Github issue 1769: Runner objects can get GCed unexpectedly
# while their future is alive.
weakref_scope = [None] # type: List[Optional[weakref.ReferenceType]]
def callback():
gc.collect(2)
weakref_scope[0]().set_result(123) # type: ignore
@gen.coroutine
def tester():
fut = Future() # type: Future[int]
weakref_scope[0] = weakref.ref(fut)
self.io_loop.add_callback(callback)
yield fut
yield gen.with_timeout(datetime.timedelta(seconds=0.2), tester())
示例4: _call_subprocess
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def _call_subprocess(self, function_to_evaluate, arguments):
restricted_tabpy = RestrictedTabPy(
self.protocol, self.port, self.logger, self.eval_timeout
)
# Exec does not run the function, so it does not block.
exec(function_to_evaluate, globals())
# 'noqa' comments below tell flake8 to ignore undefined _user_script
# name - the name is actually defined with user script being wrapped
# in _user_script function (constructed as a striong) and then executed
# with exec() call above.
if arguments is None:
future = self.executor.submit(_user_script, # noqa: F821
restricted_tabpy)
else:
future = self.executor.submit(_user_script, # noqa: F821
restricted_tabpy, **arguments)
ret = yield gen.with_timeout(timedelta(seconds=self.eval_timeout), future)
raise gen.Return(ret)
示例5: wait
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def wait(self, timeout=None):
"""Block until the internal flag is true.
Returns a Future, which raises `tornado.util.TimeoutError` after a
timeout.
"""
fut = Future()
if self._value:
fut.set_result(None)
return fut
self._waiters.add(fut)
fut.add_done_callback(lambda fut: self._waiters.remove(fut))
if timeout is None:
return fut
else:
timeout_fut = gen.with_timeout(timeout, fut, quiet_exceptions=(CancelledError,))
# This is a slightly clumsy workaround for the fact that
# gen.with_timeout doesn't cancel its futures. Cancelling
# fut will remove it from the waiters list.
timeout_fut.add_done_callback(lambda tf: fut.cancel() if not fut.done() else None)
return timeout_fut
示例6: run_updates
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def run_updates():
def func():
# try:
# print 'Checking companies...'
# update.check_companies()
# except Exception as e:
# print e
try:
print 'Checking notices...'
update.check_notices()
except:
print "Unhandled error occured :\n{}".format(traceback.format_exc())
try:
with ThreadPoolExecutor(max_workers=1) as executor:
yield gen.with_timeout(datetime.timedelta(UPDATE_PERIOD/1000.0),
executor.submit(func))
print 'run_updates done'
except gen.TimeoutError:
print 'run_updates timed out'
示例7: with_absolute_timeout
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def with_absolute_timeout(deadline, generator, **kwargs):
if deadline is None:
res = yield generator
else:
try:
res = yield gen.with_timeout(deadline, generator, **kwargs)
except gen.TimeoutError:
raise ReqlTimeoutError()
raise gen.Return(res)
# The Tornado implementation of the Cursor object:
# The `new_response` Future notifies any waiting coroutines that the can attempt
# to grab the next result. In addition, the waiting coroutine will schedule a
# timeout at the given deadline (if provided), at which point the future will be
# errored.
示例8: test_maxsize
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def test_maxsize(self):
pool = Pool("ws://localhost:8182/",
maxsize=2,
username="stephen",
password="password",
loop=self.loop,
future_class=Future)
async def go():
c1 = await pool.acquire()
c2 = await pool.acquire()
c3 = pool.acquire()
self.assertIsInstance(c3, Future)
with self.assertRaises(gen.TimeoutError):
await gen.with_timeout(timedelta(seconds=0.1), c3)
c1.conn.close()
c2.conn.close()
self.loop.run_sync(go)
示例9: test_maxsize_release
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def test_maxsize_release(self):
pool = Pool("ws://localhost:8182/",
maxsize=2,
username="stephen",
password="password",
future_class=Future)
async def go():
c1 = await pool.acquire()
c2 = await pool.acquire()
c3 = pool.acquire()
self.assertIsInstance(c3, Future)
with self.assertRaises(gen.TimeoutError):
await gen.with_timeout(timedelta(seconds=0.1), c3)
await pool.release(c2)
c3 = await c3
self.assertEqual(c2, c3)
c1.conn.close()
c2.conn.close()
c3.conn.close()
self.loop.run_sync(go)
示例10: test_maxsize_release
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def test_maxsize_release(self):
pool = Pool("ws://localhost:8182/",
maxsize=2,
username="stephen",
password="password")
c1 = yield pool.acquire()
c2 = yield pool.acquire()
c3 = pool.acquire()
self.assertIsInstance(c3, Future)
with self.assertRaises(tornado.gen.TimeoutError):
yield gen.with_timeout(timedelta(seconds=0.1), c3)
yield pool.release(c2)
c3 = yield c3
self.assertEqual(c2, c3)
c1.conn.close()
c2.conn.close()
c3.conn.close()
示例11: open
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def open(self, timeout=None):
logger.debug('koneksi ke server')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
self.stream = iostream.IOStream(sock)
try:
connect = self.stream.connect((self.host, self.port))
if timeout is not None:
yield self.with_timeout(timeout, connect)
else:
yield connect
except (socket.error, IOError, ioloop.TimeoutError) as e:
message = 'could not connect to {}:{} ({})'.format(self.host, self.port, e)
raise TTransportException(
type=TTransportException.NOT_OPEN,
message=message)
raise gen.Return(self)
示例12: post
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def post(self, *args, **kwargs):
git_list = []
with DBContext('r') as session:
git_conf = session.query(GitConf).all()
for msg in git_conf:
data_dict = model_to_dict(msg)
git_list.append(data_dict)
try:
# 超过60s 返回Timeout
res = yield gen.with_timeout(datetime.timedelta(seconds=60), self.sync_git_info(git_list),
quiet_exceptions=gen.TimeoutError)
return self.write(dict(code=0, msg=res))
except gen.TimeoutError:
return self.write(dict(code=-1, msg='TimeOut'))
示例13: _read_first_line
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def _read_first_line(self, stream, address):
try:
header_future = stream.read_until_regex(b'\r?\n\r?\n',
max_bytes=self.conn_params.max_header_size)
if self.conn_params.header_timeout is None:
header_data = yield header_future
else:
try:
header_data = yield gen.with_timeout(
stream.io_loop.time() + self.conn_params.header_timeout,
header_future,
quiet_exceptions=StreamClosedError)
except gen.TimeoutError:
stream.close()
return
# TODO: make this less hacky
stream._read_buffer[:0] = header_data
stream._read_buffer_size += len(header_data)
if header_data == b'PRI * HTTP/2.0\r\n\r\n':
self._start_http2(stream, address)
else:
super(CleartextHTTP2Server, self)._start_http1(stream, address)
except (StreamClosedError, UnsatisfiableReadError):
pass
示例14: wait
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def wait(self, timeout=None):
"""阻塞直到内部标识为true.
返回一个Future对象, 在超时之后会抛出一个 `tornado.gen.TimeoutError`
异常.
"""
if timeout is None:
return self._future
else:
return gen.with_timeout(timeout, self._future)
示例15: test_timeout
# 需要导入模块: from tornado import gen [as 别名]
# 或者: from tornado.gen import with_timeout [as 别名]
def test_timeout(self):
with self.assertRaises(gen.TimeoutError):
yield gen.with_timeout(datetime.timedelta(seconds=0.1),
Future())