48 | | else: |
49 | | mimetype = mimetypes.guess_type(fullpath)[0] |
50 | | return HttpResponse(open(fullpath, 'rb').read(), mimetype=mimetype) |
| 51 | # Respect the If-Modified-Since header. |
| 52 | statobj = os.stat(fullpath) |
| 53 | if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), |
| 54 | statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): |
| 55 | return HttpResponseNotModified() |
| 56 | mimetype = mimetypes.guess_type(fullpath)[0] |
| 57 | contents = open(fullpath, 'rb').read() |
| 58 | response = HttpResponse(contents, mimetype=mimetype) |
| 59 | response["Last-Modified"] = rfc822.formatdate(statobj[stat.ST_MTIME]) |
| 60 | return response |
| 98 | |
| 99 | def was_modified_since(header=None, mtime=0, size=0): |
| 100 | """ |
| 101 | Was something modified since the user last downloaded it? |
| 102 | |
| 103 | header |
| 104 | This is the value of the If-Modified-Since header. If this is None, |
| 105 | I'll just return True. |
| 106 | |
| 107 | mtime |
| 108 | This is the modification time of the item we're talking about. |
| 109 | |
| 110 | size |
| 111 | This is the size of the item we're talking about. |
| 112 | """ |
| 113 | try: |
| 114 | if header is None: |
| 115 | raise ValueError |
| 116 | matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header, |
| 117 | re.IGNORECASE) |
| 118 | header_mtime = rfc822.mktime_tz(rfc822.parsedate_tz( |
| 119 | matches.group(1))) |
| 120 | header_len = matches.group(3) |
| 121 | if header_len and int(header_len) != size: |
| 122 | raise ValueError |
| 123 | if mtime > header_mtime: |
| 124 | raise ValueError |
| 125 | except (AttributeError, ValueError): |
| 126 | return True |
| 127 | return False |