aiohttp: Serve single static file

Niklas picture Niklas · Dec 6, 2015 · Viewed 12.7k times · Source

How to serve a single static file (instead of an entire directory) using aiohttp?

Static file serving seems to be baked into the routing system with UrlDispatcher.add_static(), but this only serves entire directories.

(I know that I eventually should use something like nginx to serve static files in a production environment.)

Answer

thmp picture thmp · Mar 24, 2017

Currently, as of aiohttp version 2.0, the easiest way to return a single file as a response is to use the undocumented (?) FileResponse object, initialised with the path to the file, e.g.

from aiohttp import web

async def index(request):
    return web.FileResponse('./index.html')