Skip to content

Instantly share code, notes, and snippets.

@bohde
Created September 28, 2012 13:25
Show Gist options
  • Save bohde/3799842 to your computer and use it in GitHub Desktop.
Save bohde/3799842 to your computer and use it in GitHub Desktop.
An Example ModelResource using If-Modified Headers
from time import mktime
from django.utils.http import http_date, parse_http_date_safe
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.http import HttpNotModified
class IfModifiedResource(ModelResource):
def cached_obj_get(self, request=None, **kwargs):
bundle = super(IfModifiedResource, self).cached_obj_get(request, **kwargs)
if not request:
return bundle
if_modified = request.META.get('HTTP_IF_MODIFIED_SINCE')
if not if_modified:
return bundle
if_modified = parse_http_date_safe(if_modified)
# Check if object changed since the time requested
if bundle.obj.updated <= if_modified:
response = http.HttpNotModified()
response['Date'] = http_date()
raise ImmediateHttpResponse(response=response)
request._should_add_last_modified = True
return bundle
# We don't actually have a good place to check this, so this is a bit nasty
def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
response = super(IfModifiedResource, self).create_response(request, data, response_class, **response_kwargs)
if getattr(request, '_should_add_last_modified', False):
#Assuming data['updated'] is a datetime
last_modified = time.mktime(data['updated'].timetuple())
response['Last-Modified'] = http_date(last_modified)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment