Last active
November 10, 2019 20:22
-
-
Save gdamjan/d7333a4d9069af96fa4d to your computer and use it in GitHub Desktop.
Python 3.5 async/await with aiohttp, parallel or sequential
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import aiohttp | |
import asyncio | |
async def get_body(url): | |
response = await aiohttp.request('GET', url) | |
raw_html = await response.read() | |
return raw_html | |
async def main(): | |
# run them sequentially (but the loop can do other stuff in the meanwhile) | |
body1 = await get_body('http://httpbin.org/ip') | |
body2 = await get_body('http://httpbin.org/user-agent') | |
# run them in parallel | |
task1 = get_body('http://httpbin.org/ip') | |
task2 = get_body('http://httpbin.org/user-agent') | |
for body in await asyncio.gather(task1, task2): | |
print(body) | |
# OR | |
#done, pending = await asyncio.wait([task1, task2], return_when=asyncio.ALL_COMPLETED, timeout=None) | |
#for task in done: | |
# print(task.result()) | |
if __name__ == '__main__': | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aiohttp import web | |
import asyncio | |
async def handle(request): | |
name = request.match_info.get('name', "Anonymous") | |
text = "Hello, {0}\n".format(name) | |
return web.Response(body=text.encode('utf-8')) | |
async def wshandler(request): | |
ws = web.WebSocketResponse() | |
ws.start(request) | |
while True: | |
msg = await ws.receive() | |
if msg.tp == web.MsgType.text: | |
ws.send_str("Hello, {}".format(msg.data)) | |
elif msg.tp == web.MsgType.binary: | |
ws.send_bytes(msg.data) | |
elif msg.tp == web.MsgType.close: | |
break | |
return ws | |
async def init(loop): | |
app = web.Application(loop=loop) | |
app.router.add_route('GET', '/echo', wshandler) | |
app.router.add_route('GET', '/{name}', handle) | |
app.router.add_route('GET', '/', handle) | |
srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8080) | |
print("Server started at http://127.0.0.1:8080") | |
return srv | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(init(loop)) | |
loop.run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment