import asyncio
import aiohttp
loop = asyncio.get_event_loop()
presenter = {'name': 'Mantas Zimnickas'}
import asyncio
print(presenter)
import multiprocessing
import threading
import concurrent.futures
import asyncio
Below is a list of possible reasons for IO-bound performance issues:
sys.stdin
.sys.stdout
or sys.stderr
.yield
statement)from functools import partial
from concurrent.futures import ThreadPoolExecutor
def add(a, b):
return a + b
def done(a, b, future):
print('%s + %s = %s' % (a, b, future.result()))
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(add, 2, 2)
future.add_done_callback(partial(done, 2, 2))
def add(a, b):
return a + b
def main():
print('2 + 2 =', add(2, 2))
main()
@asyncio.coroutine
def add(a, b):
return a + b
@asyncio.coroutine
def main():
print('2 + 2 =', (yield from add(2, 2)))
loop.run_until_complete(main())
import aiohttp
@asyncio.coroutine
def get_size(url):
response = yield from aiohttp.request('GET', url)
return len((yield from response.read()))
@asyncio.coroutine
def main():
size = yield from get_size('https://python.org/')
print('python.org size is:', size)
loop.run_until_complete(main())
asyncio
.asyncio
shines with many concurent input/output.@asyncio.coroutine
def get_size(semaphore, url):
with (yield from semaphore):
response = yield from aiohttp.request('GET', url)
return len((yield from response.read()))
@asyncio.coroutine
def main(urls):
semaphore = asyncio.Semaphore(3)
sizes = [get_size(semaphore, url) for url in urls]
return [(yield from size) for size in asyncio.as_completed(sizes)]
urls = ['https://python.org/']
loop.run_until_complete(main(urls))
from aiohttp import web
@asyncio.coroutine
def handle(request):
return web.Response(body=b'Hello world.')
@asyncio.coroutine
def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET', '/', handle)
return (yield from loop.create_server(app.make_handler(), '127.0.0.1', 8080))
loop.run_until_complete(init(loop))
def generator():
yield 1
yield 2
return 3
def wrapper():
yield (yield from generator())
for x in wrapper():
print(x)
def coroutine():
print('b:', (yield 1))
print('b:', (yield 3))
print('b:', (yield 5))
a = coroutine()
print('a:', next(a))
print('a:', a.send(2))
print('a:', a.send(4))
@asyncio.coroutine
def my_coroutine():
print('hello')
type(my_coroutine)
type(my_coroutine())
asyncio.iscoroutinefunction(my_coroutine), asyncio.iscoroutine(my_coroutine())
deffered
from Twisted or promise
in other libraries.future = asyncio.futures.Future()
future.add_done_callback(lambda future: print("Future's done callback here."))
future.set_result("My result")
future.done()
future.exception()
future.result()
busy, ready = 0, 1
responses = [busy, busy, ready]
def callback(future, n):
if responses.pop(0) == ready:
future.set_result(n)
else:
loop.call_later(1, callback, future, n+1)
def coroutine():
future = asyncio.futures.Future()
callback(future, 1)
return future
loop.run_until_complete(coroutine())