问:如何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)