Skip to content

Instantly share code, notes, and snippets.

@xen
Last active June 18, 2021 08:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xen/139150bf6ed7ad930e22 to your computer and use it in GitHub Desktop.
Save xen/139150bf6ed7ad930e22 to your computer and use it in GitHub Desktop.
HTTP cache headers decorator for Flask
# 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))
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