How to add HTTP Cache-Control Headers in Flask

Image for post
Image for post
Kulandru mor / CC0

Using caching can vastly improve the performance of your applications. There are different types of caching options available while developing Web applications but HTTP caching is one of the simplest ways to improve the performance of your application.

As described in MDN web docs:

The HTTP/1.1 general-header field is used to specify directives for caching mechanisms in both requests and responses.

In this short post, I will show you how you could use decorators in Flask to cleanly add HTTP cache-control headers to your APIs.

Firstly, add a decorator method in your file. The decorator adds the cache headers to the Flask response. The method takes two parameters:

  • minutes: To define the age and expiry of the cache
  • content_type: To define the content type of the response.
from datetime import datetime, date, timedelta
from functools import wraps
from flask import Response

def docache(minutes=5, content_type='application/json; 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(minutes=minutes)
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(60 * minutes))
return rsp
return wrapped_f
return fwrap

Using decorators makes life easier and now you can add HTTP cache control headers in any of your API responses with just a single line of code. You can simply annotate the method with to add the headers.

from flask import json
from .utils import docache


@api.route('/summary')
@docache(minutes=5, content_type='application/json')
def get_summary():
return json.dumps(range({"count": 5}))

That’s it. Now if your CDN is configured properly, you would start seeing cache hits for your API calls.

Image for post
Image for post

Written by

Grad Student at ASU | Student Researcher at The Luminosity Lab | Ex Senior Software Engineer, Zeta | Volunteer, Wikimedia Foundation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store