aiohttp: Serve single static file

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">
    

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, 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')