【发布时间】:2015-04-05 12:42:11
【问题描述】:
我正在尝试利用 Python 的新 asyncio 库来发送异步 HTTP 请求。我想在发送每个请求之前等待几毫秒(timeout 变量) - 但当然 - 异步发送它们,而不是在每个请求发送后等待响应。
我正在做类似以下的事情:
@asyncio.coroutine
def handle_line(self, line, destination):
print("Inside! line {} destination {}".format(line, destination))
response = yield from aiohttp.request('POST', destination, data=line,
headers=tester.headers)
print(response.status)
return (yield from response.read())
@asyncio.coroutine
def send_data(self, filename, timeout):
destination='foo'
logging.log(logging.DEBUG, 'sending_data')
with open(filename) as log_file:
for line in log_file:
try:
json_event = json.loads(line)
except ValueError as e:
print("Error parsing json event")
time.sleep(timeout)
yield from asyncio.async(self.handle_line(json.dumps(json_event), destination))
loop=asyncio.get_event_loop().run_until_complete(send_data('foo.txt', 1))
我得到的输出(通过打印 200 个响应)看起来像这段代码正在同步运行。我做错了什么?
【问题讨论】:
标签: python python-3.x asynchronous python-asyncio