TEL:400-8793-956
当前位置:程序、服务器

使用aiohttp作为Web服务器设置静态资源的默认Cache-Control标头

提问者: 近期获赞: 浏览人数: 发布时间:2021-03-10 09:53:03

 问:如何Cache-Control: no-cache为静态文件设置标头,以使aiohttpWeb应用程序的开发更加舒适?我研究了几个小时才得到这个结果。有没有更简单的方法?

 
 
答:from aiohttp import web
 
routes = [
    web.get('/hot-reload', hot_reload),
    web.get('/demo/index', demo.index),
    web.get('/demo/fetch', demo.fetch),
    web.static('/foo', '/foo', name='static1'),
    web.static('/', '/public', name='static2'),
]
 
@web.middleware
async def cache_control(request: web.Request, handler):
    response: web.Response = await handler(request)
    resource_name = request.match_info.route.name
    if resource_name and resource_name.startswith('static'):
        response.headers.setdefault('Cache-Control', 'no-cache')
    return response
 
app = web.Application(middlewares=[cache_control])
app.add_routes(routes)
上一篇: 如何将Application Insights customEvents表移至postgres数据库?
下一篇: 使用Apache MethodUtils调用私有方法