aiohttp:提供单个静态文件

aiohttp: Serve single static file

如何使用 aiohttp 提供单个静态文件(而不是整个目录)?

静态文件服务似乎已通过 UrlDispatcher.add_static() 融入路由系统,但这仅服务于整个目录。

(我知道我最终应该使用 nginx 之类的东西在生产环境中提供静态文件。)

目前没有内置的方法可以做到这一点;但是,有计划 add this feature.

我写了应用程序,它在客户端(angular 路由器)上处理 uri。

为了服务 webapp,我使用了稍微不同的工厂:

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

目前,从 aiohttp 版本 2.0 开始,return 将单个文件作为响应的最简单方法是使用未记录的 (?) FileResponse 对象,使用文件路径初始化, 例如

from aiohttp import web

async def index(request):
    return web.FileResponse('./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">