Skip to content

Instantly share code, notes, and snippets.

@liddiard
Created April 23, 2015 22:28
Show Gist options
  • Save liddiard/47beafa107cdf97747e5 to your computer and use it in GitHub Desktop.
Save liddiard/47beafa107cdf97747e5 to your computer and use it in GitHub Desktop.
Custom full-response caching setup for Django Rest Framework list view where keys are unique URLs. Opted to not continue with the invalidation on model save code cause cache invalidation is hard.
def list(self, request, *args, **kwargs):
# get the base url without any query params
url = request.path
params = []
# build a list of 2-value tuples which contains query params
for key, value in request.GET.iteritems():
params.append((key, value))
if params:
# sort the params so e.g., ?bunny=cute&fox=sly is treated as the
# same key as ?fox=sly&bunny=cute
params.sort()
# encode query params and append them to the base url
url += urllib.urlencode(params)
print url
# see if request url is already in the cache
response_data = cache.get(url)
if response_data:
print "cached"
# return a response with the cached data
return Response(response_data)
else:
print "not cached"
# do all the business logic (database lookups, serialization,
# etc.) that this method would do normally
response = super(AuthorViewSet, self).list(request, *args, **kwargs)
# cache the response for next time
cache.set(url, response.data)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment