Created
May 23, 2020 19:11
-
-
Save ryan-hallman/c6fa18d6847ef06d548f8de94ec29102 to your computer and use it in GitHub Desktop.
This file contains 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
""" | |
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