Skip to content

Instantly share code, notes, and snippets.

@ryan-hallman
Created May 23, 2020 19:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryan-hallman/c6fa18d6847ef06d548f8de94ec29102 to your computer and use it in GitHub Desktop.
Save ryan-hallman/c6fa18d6847ef06d548f8de94ec29102 to your computer and use it in GitHub Desktop.
"""
This Python Flask view decorator can be used to control browser cache settings
which is useful for REST APIs where IE and a few others tend to cache
the response rather than update the data.
"""
# Example usage:
@app.route('/my_api')
@control_cache(hours=0, content_type='application/json')
def my_api():
return json.dumps({'Hello World': 'Hello Back'}
def control_cache(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