Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aiohttp: Serve single static file

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

like image 819
Niklas Avatar asked Dec 06 '15 19:12

Niklas


4 Answers

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')
like image 164
thmp Avatar answered Oct 21 '22 23:10

thmp


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"))
like image 24
eri Avatar answered Oct 21 '22 22:10

eri


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

like image 21
Jashandeep Sohi Avatar answered Oct 21 '22 23:10

Jashandeep Sohi


# 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">
    
like image 38
Michael Kor Avatar answered Oct 22 '22 00:10

Michael Kor