Created
September 28, 2012 13:25
-
-
Save bohde/3799842 to your computer and use it in GitHub Desktop.
An Example ModelResource using If-Modified Headers
This file contains hidden or 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
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