Last active
June 18, 2021 08:43
-
-
Save xen/139150bf6ed7ad930e22 to your computer and use it in GitHub Desktop.
HTTP cache headers decorator for Flask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example | |
from flask import json | |
from .utils import docache | |
@api.route('/jsonmethod', defaults={'count': 10}) | |
@docache(hours=48, content_type='application/json') | |
def get_count(count): | |
# can be useable with JSON APIs | |
return json.dumps(range(count)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime, date, timedelta | |
from functools import wraps | |
from flask import Response | |
def docache(hours=10, content_type='text/html; charset=utf-8'): | |
""" Flask decorator that allow to set Expire and Cache headers. """ | |
def fwrap(f): | |
@wraps(f) | |
def wrapped_f(*args, **kwargs): | |
r = f(*args, **kwargs) | |
then = datetime.now() + timedelta(hours=hours) | |
rsp = Response(r, content_type=content_type) | |
rsp.headers.add('Expires', then.strftime("%a, %d %b %Y %H:%M:%S GMT")) | |
rsp.headers.add('Cache-Control', 'public,max-age=%d' % int(3600 * hours)) | |
return rsp | |
return wrapped_f | |
return fwrap |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment