Aiohttp: Serve a single static file

How to serve one static file (instead of the whole directory) using aiohttp?

It seems that static file processing has been baked into the routing system with UrlDispatcher.add_static () , but it only serves whole directories.

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

+6
source share
3 answers

There is currently no built-in way to do this; however, there are plans to add this feature .

+4
source

Currently, from version aiohttp version 2.0, the easiest way to return a single file as an answer is to use an undocumented (?) FileResponse object initialized with a file path, for example

 from aiohttp import web async def index(request): return web.FileResponse('./index.html') 
+6
source

I wrote an application that handles uri on the client (angular router).

To serve webapp, I used a 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")) 
+1
source

All Articles