如何从龙卷风未来对象中获取内容
How to get content from tornado future object
我真的对 tornado 框架和 'future' 对象感到困惑。
所以我想通过进行 http 调用来获得异步响应
代码是:
class TestAsyncHttp(object):
def __init__(self):
self._http_client = httpclient.AsyncHTTPClient()
@gen.coroutine
def get_response(self, params)
response = yield self._request(
method='POST',
endpoint='test'
data=params
)
raise gen.Return(response)
@gen.coroutine
def _request(self, method, endpoint, data):
url = self._make_url(endpoint) #this includes the port..
headers = self._load_headers()
request = httpclient.HTTPRequest(
url,
method=method,
headers=header,
body=json.dump(data)
)
response = yield self._http_client.fetch(request)
raise gen.Return(response)
问题是,完成这个之后,我该如何测试?
我试着写了一个包含...:[=12=]
import json
with open('test/request.json') as json_file:
request_json = json.loads(json_file.read())
def get_response():
x = TestAsyncHttp()
ret = yield x.get_response(request_json)
body = ret.body
print body['value']
get_response
但是后来我'python "path-to-the-script"'
没有任何输出。
如果我刚进入 "python" 环境,我得到 "future" object doesn't have getitem
..如何从未来获取内容..?
谢谢!
使用 run_sync
到 运行 同步方式的异步协程:
def get_response():
x = TestAsyncHttp()
ret = IOLoop.current().run_sync(lambda: x.get_response(request_json))
body = ret.body
print body['value']
此处需要lambda
只是为了传递request_json
参数。如果 get_response
没有参数,你可以改为:
ret = IOLoop.current().run_sync(x.get_response)
我真的对 tornado 框架和 'future' 对象感到困惑。 所以我想通过进行 http 调用来获得异步响应 代码是:
class TestAsyncHttp(object):
def __init__(self):
self._http_client = httpclient.AsyncHTTPClient()
@gen.coroutine
def get_response(self, params)
response = yield self._request(
method='POST',
endpoint='test'
data=params
)
raise gen.Return(response)
@gen.coroutine
def _request(self, method, endpoint, data):
url = self._make_url(endpoint) #this includes the port..
headers = self._load_headers()
request = httpclient.HTTPRequest(
url,
method=method,
headers=header,
body=json.dump(data)
)
response = yield self._http_client.fetch(request)
raise gen.Return(response)
问题是,完成这个之后,我该如何测试?
我试着写了一个包含...:[=12=]
import json
with open('test/request.json') as json_file:
request_json = json.loads(json_file.read())
def get_response():
x = TestAsyncHttp()
ret = yield x.get_response(request_json)
body = ret.body
print body['value']
get_response
但是后来我'python "path-to-the-script"' 没有任何输出。 如果我刚进入 "python" 环境,我得到 "future" object doesn't have getitem ..如何从未来获取内容..?
谢谢!
使用 run_sync
到 运行 同步方式的异步协程:
def get_response():
x = TestAsyncHttp()
ret = IOLoop.current().run_sync(lambda: x.get_response(request_json))
body = ret.body
print body['value']
此处需要lambda
只是为了传递request_json
参数。如果 get_response
没有参数,你可以改为:
ret = IOLoop.current().run_sync(x.get_response)