在浏览器中管理缓存文件

时间:2017-07-21 12:17:41

标签: python python-3.x http caching aiohttp

我希望管理我的静态文件在浏览器中缓存或由于文件时间戳而作为新文件下载。

因此,如果源文件(js,css,png ....)的更改时间高于浏览器缓存文件时间标志,脚本将发送响应200(下载文件)否则304(没有更改 - 使用缓存文件)

所以我编辑了这样的aiohttp脚本:

import pytz
@partial(app.router.add_route, 'GET', '/static/{journey:.*}')
async def handle(request):
    fullpath = os.path.join(os.path.dirname(__file__), 'static/'+request.match_info['journey'])
    response = web.Response(headers={'Content-Disposition': 'Attachment','filename': fullpath.split('/')[-1]})
    time = request.if_modified_since
    status = 200
    #get file
    try:
        timestamp = os.path.getmtime(fullpath)
        timestamp = datetime.datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
    except OSError as e:
        print(e)
        status = 404
        timestamp = False

    if time is None or timestamp is None:
        response.last_modified = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
    else:
        if timestamp and timestamp < time:
            status = 304

    if status == 200:
        t = fullpath.split('.')[-1]
        if t in ['png', 'jpg', 'gif']:
            response.content_type = 'image/{}'.format(t)
        elif t == 'js':
            response.content_type = 'application/javascript'
        async with aiofiles.open(fullpath, mode='rb') as f:
            response.body = await f.read()

    response.set_status(status)
    return response

并删除了

app.router.add_static('/static', 'static')

一切正常但我认为设置文件内容的代码部分由于阅读而没有那么好的解决方案。

async with aiofiles.open(fullpath, mode='rb') as f:
    response.body = await f.read()

有没有人知道如何在aiohttp中处理这个问题? 谢谢Michal

0 个答案:

没有答案