import io from concurrent.futures import ProcessPoolExecutor from PIL import Image from aiohttp import web def resize(image_data): """Perform the actual resizing using Pillow blocking functions""" img = Image.open(io.BytesIO(image_data)) img.thumbnail((100, 100), Image.ANTIALIAS) buf = io.BytesIO() img.save(buf, 'PNG') return buf.getvalue() class Handler(web.View): def __init__(self, request): super().__init__(request) self.executor = ProcessPoolExecutor() async def get(self): return web.Response(body=b'''

Resize an image

''', content_type='text/html') async def post(self): data = await self.request.post() thumbnail = await self.request.app.loop.run_in_executor(self.executor, resize, data['image'].file.read()) return web.Response(body=thumbnail, content_type='image/png') app = web.Application() app.router.add_route('*', '/', Handler) web.run_app(app)