23

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.)

Niklas
  • 3,753
  • 4
  • 21
  • 29

4 Answers4

39

You can use aiohttp.web.FileResponse, initialised with the path to the file, e.g.

from aiohttp import web

async def index(request):
    return web.FileResponse('./index.html')
Will Da Silva
  • 6,386
  • 2
  • 27
  • 52
thmp
  • 601
  • 6
  • 7
8

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"))
Max Alibaev
  • 681
  • 7
  • 17
eri
  • 3,133
  • 1
  • 23
  • 35
6

Currently there is no built-in way of doing this; however, there are plans in motion to add this feature.

Jashandeep Sohi
  • 4,903
  • 2
  • 23
  • 25
3
# server
local_dir = os.path.join(os.path.dirname(__file__), "static")
app.router.add_static('/static', local_dir)

# HTML
<a href="/static/main.css">
    
Pavel Vlasov
  • 4,206
  • 6
  • 41
  • 54