Как не надо делать, чтобы ваш open-source продукт стал пользоваться успехом
Андрей Светлов, LevelUP
import json
import asyncio
import aiohttp
URL = 'http://p.corp.mail.ru/api/json'
@asyncio.coroutine
def get_free_parking_places():
response = yield from aiohttp.request('GET', URL)
body = yield from response.read_and_close()
return json.loads(body.decode())['places']
@asyncio.coroutine
def main():
result = yield from get_free_parking_places()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
@coroutine
def sleep(delay, result=None, *, loop=None):
"""Coroutine that completes after a given time (in seconds)."""
future = futures.Future(loop=loop)
h = future._loop.call_later(delay, future.set_result, result)
try:
return (yield from future)
finally:
h.cancel()
@asyncio.coroutine
def print_http_headers(url):
url = urllib.parse.urlsplit(url)
reader, writer = yield from asyncio.open_connection(url.hostname, 80)
query = (
'HEAD {url.path} HTTP/1.0\r\n'
'Host: {url.hostname}\r\n'
'\r\n'
).format(url=url)
writer.write(query.encode('latin-1'))
while True:
line = yield from reader.readline()
if not line:
break
print(line.decode('latin1').rstrip())
yield from asyncio.create_subprocess_shell(...)
yield from asyncio.create_subprocess_exec(...)
import asyncio
@asyncio.coroutine
def test():
print("never scheduled")
test()
export PYTHONASYNCIODEBUG=1
(env) MacAir:env fz$ PYTHONASYNCIODEBUG=1 python test.py
Coroutine 'test' defined at test.py:3 was never yielded from
class MyTest(unittest.TestCase): def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) def tearDown(self): self.loop.close() def test_some_case():
@asyncio.coroutine def run(): yield from asyncio.sleep(0.5, loop=self.loop) self.loop.run_until_complete(run())