本文整理汇总了Python中tornado.concurrent.Future.set_result方法的典型用法代码示例。如果您正苦于以下问题:Python Future.set_result方法的具体用法?Python Future.set_result怎么用?Python Future.set_result使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.concurrent.Future
的用法示例。
在下文中一共展示了Future.set_result方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: put
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def put(self, value):
"""Puts an item into the queue.
Returns a Future that resolves to None once the value has been
accepted by the queue.
"""
io_loop = IOLoop.current()
new_hole = Future()
new_put = Future()
new_put.set_result(new_hole)
with self._lock:
self._put, put = new_put, self._put
answer = Future()
def _on_put(future):
if future.exception(): # pragma: no cover (never happens)
return answer.set_exc_info(future.exc_info())
old_hole = put.result()
old_hole.set_result(Node(value, new_hole))
answer.set_result(None)
io_loop.add_future(put, _on_put)
return answer
示例2: wait
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> "Future[None]":
"""Block until the internal flag is true.
Returns a Future, 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: get_tweets
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def get_tweets(username):
result_future = Future()
"""helper function to fetch 200 tweets for a user with @username
"""
TWITTER_URL = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
'''
curl --get 'https://api.twitter.com/1.1/statuses/user_timeline.json' --data 'count=200&screen_name=twitterapi' --header 'Authorization: OAuth oauth_consumer_key="BlXj0VRgkpUOrN3b6vTyJu8YB", oauth_nonce="9cb4b1aaa1fb1d79e0fbd9bc8b33f82a", oauth_signature="SrJxsOCzOTnudKQMr4nMQ0gDuRk%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1456006969", oauth_token="701166849883373568-bqVfk8vajGxWIlKDe94CRjMJtBvwdQQ", oauth_version="1.0"' --verbose
'''
auth = OAuth1('BlXj0VRgkpUOrN3b6vTyJu8YB', 'qzkhGeWIYVXod9umMuinHF2OFmJxiucQspX5JsA7aH8xs5t4DT',
'701166849883373568-bqVfk8vajGxWIlKDe94CRjMJtBvwdQQ', 'y3gx0F5fLyIQQFNDev8JtpPKpEUmyy3mMibxCcTK2kbZZ')
data = {'count': 200,
'screen_name': username}
r = requests.get(url=TWITTER_URL, params=data, auth=auth)
data = r.json()
if 'errors' in data:
raise Exception
res = []
for item in data:
if 'retweeted_status' not in item.keys():
res.append(item)
result_future.set_result(res)
return result_future
示例4: wechat_api_mock
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def wechat_api_mock(client, request, *args, **kwargs):
url = urlparse(request.url)
path = url.path.replace('/cgi-bin/', '').replace('/', '_')
if path.startswith('_'):
path = path[1:]
res_file = os.path.join(_FIXTURE_PATH, '%s.json' % path)
content = {
'errcode': 99999,
'errmsg': 'can not find fixture %s' % res_file,
}
headers = {
'Content-Type': 'application/json'
}
try:
with open(res_file, 'rb') as f:
content = f.read().decode('utf-8')
except (IOError, ValueError) as e:
content['errmsg'] = 'Loads fixture {0} failed, error: {1}'.format(
res_file,
e
)
content = json.dumps(content)
buffer = StringIO(content)
resp = HTTPResponse(
request,
200,
headers=headers,
buffer=buffer,
)
future = Future()
future.set_result(resp)
return future
示例5: ManualCapClient
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [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: acquire
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def acquire(self, pool_need_log=False):
"""Occupy free connection"""
future = Future()
while True:
if self.free:
conn = self.free.pop()
if conn.valid:
self.busy.add(conn)
else:
self.dead.add(conn)
continue
future.set_result(conn)
conn.connection_need_log = pool_need_log
log.debug("Acquired free connection %s", conn.fileno)
return future
elif self.busy:
log.debug("No free connections, and some are busy - put in waiting queue")
self.waiting_queue.appendleft(future)
return future
elif self.pending:
log.debug("No free connections, but some are pending - put in waiting queue")
self.waiting_queue.appendleft(future)
return future
else:
log.debug("All connections are dead")
return None
示例7: test_moment
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def test_moment(self):
calls = []
@gen.coroutine
def f(name, yieldable):
for i in range(5):
calls.append(name)
yield yieldable
# First, confirm the behavior without moment: each coroutine
# monopolizes the event loop until it finishes.
immediate = Future() # type: Future[None]
immediate.set_result(None)
yield [f("a", immediate), f("b", immediate)]
self.assertEqual("".join(calls), "aaaaabbbbb")
# With moment, they take turns.
calls = []
yield [f("a", gen.moment), f("b", gen.moment)]
self.assertEqual("".join(calls), "ababababab")
self.finished = True
calls = []
yield [f("a", gen.moment), f("b", immediate)]
self.assertEqual("".join(calls), "abbbbbaaaa")
示例8: test_future_list
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def test_future_list(self):
d = Doc('a')
f = Future()
f.set_result([etree.Comment('ccc'), etree.Element('bbb')])
d.put(f)
self.assertXmlEqual(d.to_etree_element(), """<?xml version='1.0'?>\n<a><!--ccc--><bbb/></a>""")
示例9: test_range_query
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def test_range_query(self):
# Mock cassandra response
async_response = Future()
async_response.set_result([
('keyA', 'c1', '1'), ('keyA', 'c2', '2'),
('keyB', 'c1', '4'), ('keyB', 'c2', '5'),
('keyC', 'c1', '7'), ('keyC', 'c2', '8')
])
self.execute_mock.return_value = async_response
# Call function under test
columns = ['c1', 'c2']
result = yield self.db.range_query("tableZ", columns, "keyA", "keyC", 5)
# Make sure cassandra interface prepared good query
query = self.execute_mock.call_args[0][0]
parameters = self.execute_mock.call_args[1]["parameters"]
self.assertEqual(
query.query_string,
'SELECT * FROM "tableZ" WHERE '
'token(key) >= %s AND '
'token(key) <= %s AND '
'column1 IN %s '
'LIMIT 10 ' # 5 * number of columns
'ALLOW FILTERING')
self.assertEqual(parameters, (b'keyA', b'keyC', ['c1', 'c2']) )
# And result matches expectation
self.assertEqual(result, [
{'keyA': {'c1': '1', 'c2': '2'}},
{'keyB': {'c1': '4', 'c2': '5'}},
{'keyC': {'c1': '7', 'c2': '8'}}
])
示例10: test_get
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def test_get(self):
# Mock cassandra response
async_response = Future()
async_response.set_result([
('a', 'c1', '1'), ('a', 'c2', '2'), ('a', 'c3', '3'),
('b', 'c1', '4'), ('b', 'c2', '5'), ('b', 'c3', '6'),
('c', 'c1', '7'), ('c', 'c2', '8'), ('c', 'c3', '9'),
])
self.execute_mock.return_value = async_response
# Call function under test
keys = ['a', 'b', 'c']
columns = ['c1', 'c2', 'c3']
result = yield self.db.batch_get_entity('table', keys, columns)
# Make sure cassandra interface prepared good query
query = self.execute_mock.call_args[0][0]
parameters = self.execute_mock.call_args[1]["parameters"]
self.assertEqual(
query.query_string,
'SELECT * FROM "table" WHERE key IN %s and column1 IN %s')
self.assertEqual(parameters, ([b'a', b'b', b'c'], ['c1', 'c2', 'c3']) )
# And result matches expectation
self.assertEqual(result, {
'a': {'c1': '1', 'c2': '2', 'c3': '3'},
'b': {'c1': '4', 'c2': '5', 'c3': '6'},
'c': {'c1': '7', 'c2': '8', 'c3': '9'}
})
示例11: setUp
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def setUp(self):
AsyncTestCase.setUp(self)
return_value = {
'label': 'A Label',
'comment': 'A Comment',
'depiction': 'A URL'
}
future = Future()
future.set_result(return_value)
self._wrapped_fn = Mock(return_value=future)
self._decorated_fn = cache_facts(self._wrapped_fn)
#setup a function with a value to be cached
#and decorate it with the decorated under test
@cache_facts
def intense_fact_processing(uri):
return {
'label': 'A Label',
'comment': 'A Comment',
'depiction': 'A URL',
'uri': uri
}
self.intense_fact_processing = intense_fact_processing
示例12: queue_get
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def queue_get():
future = Future()
try:
future.set_result(queue.get_nowait())
except QueueEmpty:
pass
return future
示例13: _get_conn
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def _get_conn(self): # -> Future[connection]
now = self.io_loop.time()
# Try to reuse in free pool
while self._free_conn:
conn = self._free_conn.popleft()
if now - conn.connected_time > self.max_recycle_sec:
self._close_async(conn)
continue
log.debug("Reusing connection from pool: %s", self.stat())
fut = Future()
fut.set_result(conn)
return fut
# Open new connection
if self.max_open == 0 or self._opened_conns < self.max_open:
self._opened_conns += 1
log.debug("Creating new connection: %s", self.stat())
fut = connect(**self.connect_kwargs)
fut.add_done_callback(self._on_connect) # self._opened_conns -=1 on exception
return fut
# Wait to other connection is released.
fut = Future()
self._waitings.append(fut)
return fut
示例14: test_rank_calls_sort_and_returns_output
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [as 别名]
def test_rank_calls_sort_and_returns_output(self):
#setup the response from the summarum endpoint
expected_result = [
('a', 'b', 10.0),
('c', 'd', 1.0)
]
future = Future()
future.set_result(expected_result)
self.endpoint.fetch_and_parse = Mock(return_value=future)
#setup the response return value from the sort call
expected_ranked_facts = {
'predicate': {},
'objects': []
}
self.ranking_service.sort = Mock(return_value = expected_ranked_facts)
#call the function under test
facts = {}
ranked_facts = yield self.ranking_service.rank(facts)
#check that sort was called
self.ranking_service.sort.assert_called_once_with(facts)
#check that rank returns the output from sort
self.assertEquals(ranked_facts, expected_ranked_facts)
示例15: _start_processing_requests
# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_result [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))