如何使用 aiohttp 提供单个静态文件(而不是整个目录)?
静态文件服务似乎通过UrlDispatcher.add_static()被烘焙到路由系统中,但这仅服务于整个目录。
(我知道我最终应该使用 nginx 之类的东西在生产环境中提供静态文件。)
如何使用 aiohttp 提供单个静态文件(而不是整个目录)?
静态文件服务似乎通过UrlDispatcher.add_static()被烘焙到路由系统中,但这仅服务于整个目录。
(我知道我最终应该使用 nginx 之类的东西在生产环境中提供静态文件。)
目前,从 aiohttp 2.0 版开始,返回单个文件作为响应的最简单方法是使用未记录的 (?)FileResponse
对象,该对象使用文件的路径进行初始化,例如
from aiohttp import web
async def index(request):
return web.FileResponse('./index.html')
我编写了应用程序,它处理客户端(角度路由器)上的 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"))
目前没有内置的方法可以做到这一点;但是,有计划添加此功能。
# 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">