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.)
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')
                        I wrote App, that handles uri on client (angular router).
To serve webapp i used slightly different factory:
def index_factory(path,filename):
    async def static_view(request):
        # prefix not needed
        route = web.StaticRoute(None, '/', path)
        request.match_info['filename'] = filename
        return await route.handle(request)
    return static_view
# json-api
app.router.add_route({'POST','GET'}, '/api/{collection}', api_handler)
# other static
app.router.add_static('/static/', path='../static/', name='static')
# index, loaded for all application uls.
app.router.add_get('/{path:.*}', index_factory("../static/ht_docs/","index.html"))
                        Currently there is no built-in way of doing this; however, there are plans in motion to add this feature.
# include handler path
app['static_root_url'] = '/static'    
# path dir of static file
STATIC_PATH = os.path.join(os.path.dirname(__file__), "static")    
app.router.add_static('/static/', STATIC_PATH, name='static')
# include in template
<link href="{{static('/main.css')}}" rel="stylesheet">
    
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With