简体   繁体   中英

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

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, eg

from aiohttp import web

async def index(request):
    return web.FileResponse('./index.html')

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM