Created
November 17, 2019 22:06
-
-
Save snorfalorpagus/f10c05ea6b46b9881557a125137a07df to your computer and use it in GitHub Desktop.
Running blocking tasks in a thread with aiohttp
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 asyncio | |
from aiohttp import web | |
from concurrent.futures import ThreadPoolExecutor | |
import time | |
def blocking_func(seconds: int) -> int: | |
time.sleep(seconds) | |
return seconds | |
async def view_page(request: web.Request): | |
seconds = int(request.query.get("seconds", 5)) | |
executor = request.app["executor"] | |
loop = asyncio.get_event_loop() | |
task = loop.run_in_executor(executor, blocking_func, seconds) | |
completed, pending = await asyncio.wait([task]) | |
result = task.result() | |
return web.Response(text=f"Waited {result} second(s).") | |
def create_app(): | |
app = web.Application() | |
app.add_routes([web.get("/", view_page)]) | |
executor = ThreadPoolExecutor(max_workers=3) | |
app["executor"] = executor | |
return app | |
if __name__ == "__main__": | |
app = create_app() | |
web.run_app(app) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment