PageRenderTime 165ms CodeModel.GetById 159ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/django/middleware/http.py

https://code.google.com/p/mango-py/
Python | 36 lines | 20 code | 4 blank | 12 comment | 12 complexity | 7e8f5beba78d8959ad64e9ab7e870729 MD5 | raw file
 1from django.core.exceptions import MiddlewareNotUsed
 2from django.utils.http import http_date, parse_http_date_safe
 3
 4class ConditionalGetMiddleware(object):
 5    """
 6    Handles conditional GET operations. If the response has a ETag or
 7    Last-Modified header, and the request has If-None-Match or
 8    If-Modified-Since, the response is replaced by an HttpNotModified.
 9
10    Also sets the Date and Content-Length response-headers.
11    """
12    def process_response(self, request, response):
13        response['Date'] = http_date()
14        if not response.has_header('Content-Length'):
15            response['Content-Length'] = str(len(response.content))
16
17        if response.has_header('ETag'):
18            if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
19            if if_none_match == response['ETag']:
20                # Setting the status is enough here. The response handling path
21                # automatically removes content for this status code (in
22                # http.conditional_content_removal()).
23                response.status_code = 304
24
25        if response.has_header('Last-Modified'):
26            if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')
27            if if_modified_since is not None:
28                if_modified_since = parse_http_date_safe(if_modified_since)
29            if if_modified_since is not None:
30                last_modified = parse_http_date_safe(response['Last-Modified'])
31                if last_modified is not None and last_modified <= if_modified_since:
32                    # Setting the status code is enough here (same reasons as
33                    # above).
34                    response.status_code = 304
35
36        return response