我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.http.http_date()。
def serve(self, request, path): # the following code is largely borrowed from `django.views.static.serve` # and django-filetransfers: filetransfers.backends.default fullpath = os.path.join(settings.PRIVATE_MEDIA_ROOT, path) if not os.path.exists(fullpath): raise Http404('"{0}" does not exist'.format(fullpath)) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) content_type = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified(content_type=content_type) response = HttpResponse(open(fullpath, 'rb').read(), content_type=content_type) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) # filename = os.path.basename(path) # response['Content-Disposition'] = smart_str(u'attachment; filename={0}'.format(filename)) return response
def serve(self, request, file_obj, **kwargs): fullpath = file_obj.path # the following code is largely borrowed from `django.views.static.serve` # and django-filetransfers: filetransfers.backends.default if not os.path.exists(fullpath): raise Http404('"%s" does not exist' % fullpath) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) content_type_key = 'mimetype' if LTE_DJANGO_1_4 else 'content_type' response_params = {content_type_key: self.get_mimetype(fullpath)} if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified(**response_params) response = HttpResponse(open(fullpath, 'rb').read(), **response_params) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) self.default_headers(request=request, response=response, file_obj=file_obj, **kwargs) return response
def process_response(self, request, response): response['Date'] = http_date() if not response.streaming and not response.has_header('Content-Length'): response['Content-Length'] = str(len(response.content)) etag = response.get('ETag') last_modified = response.get('Last-Modified') if last_modified: last_modified = parse_http_date_safe(last_modified) if etag or last_modified: return get_conditional_response( request, etag=unquote_etag(etag), last_modified=last_modified, response=response, ) return response
def __call__(self, request, *args, **kwargs): """ Copied from django.contrib.syndication.views.Feed Supports file_name as a dynamic attr. """ try: obj = self.get_object(request, *args, **kwargs) except ObjectDoesNotExist: raise Http404('Feed object does not exist.') feedgen = self.get_feed(obj, request) response = HttpResponse(content_type=feedgen.mime_type) if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'): # if item_pubdate or item_updateddate is defined for the feed, set # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED response['Last-Modified'] = http_date( timegm(feedgen.latest_post_date().utctimetuple())) feedgen.write(response, 'utf-8') filename = self._get_dynamic_attr('file_name', obj) if filename: response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response
def get(self, request, name): db_file = get_object_or_404(DBFile.objects.defer('content'), name=name) mtime = time.mktime(db_file.updated_on.timetuple()) modified = was_modified_since( header=self.request.META.get('HTTP_IF_MODIFIED_SINCE'), mtime=mtime, size=db_file.size) if not modified: return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(db_file.name) content_type = content_type or 'application/octet-stream' response = HttpResponse(db_file.content, content_type=content_type) response['Last-Modified'] = http_date(mtime) response['Content-Length'] = db_file.size if encoding: response['Content-Encoding'] = encoding return response
def process_response(self, request, response): response['Date'] = http_date() if not response.streaming and not response.has_header('Content-Length'): response['Content-Length'] = str(len(response.content)) etag = response.get('ETag') last_modified = response.get('Last-Modified') if last_modified: last_modified = parse_http_date_safe(last_modified) if etag or last_modified: return get_conditional_response( request, etag=etag, last_modified=last_modified, response=response, ) return response
def get(self, request, mode_id=None): mode_id = int(mode_id) if not (mode_id in Mode.stat_v1_ids): return HttpResponse(status=404) last_updated = to_unix(cache_value("ranking_stats_last_modified", 600, ranking_stats_last_modified)) now = to_unix(utcnow()) try: if_modified_since = parse_http_date(request.META['HTTP_IF_MODIFIED_SINCE']) except (ValueError, KeyError): if_modified_since = 0 if if_modified_since >= last_updated: response = HttpResponse("", content_type="application/json", status=304) else: response = HttpResponse(cache_value("ranking_stats_%d" % mode_id, 600, rankings_view_client, 'ranking_stats', mode_id), content_type="application/json") response['Cache-Control'] = "max-age=86400" response['Date'] = http_date(now) response['Expires'] = http_date(now + 86400) response['Last-Modified'] = http_date(last_updated) return response
def patch_response_headers(response, cache_timeout=None): """ Adds some useful headers to the given HttpResponse object: ETag, Last-Modified, Expires and Cache-Control Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default. """ if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS if cache_timeout < 0: cache_timeout = 0 # Can't have max-age negative if settings.USE_ETAGS and not response.has_header('ETag'): if hasattr(response, 'render') and callable(response.render): response.add_post_render_callback(_set_response_etag) else: response = _set_response_etag(response) if not response.has_header('Last-Modified'): response['Last-Modified'] = http_date() if not response.has_header('Expires'): response['Expires'] = http_date(time.time() + cache_timeout) patch_cache_control(response, max_age=cache_timeout)
def test_not_modified(self): server = DefaultServer() request = Mock() request.META = {'HTTP_IF_MODIFIED_SINCE': http_date(time.time())} response = server.serve(request, self.filer_file.file) self.assertTrue(isinstance(response, HttpResponseNotModified))
def __call__(self, request, *args, **kwargs): try: obj = self.get_object(request, *args, **kwargs) except ObjectDoesNotExist: raise Http404('Feed object does not exist.') feedgen = self.get_feed(obj, request) response = HttpResponse(content_type=feedgen.content_type) if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'): # if item_pubdate or item_updateddate is defined for the feed, set # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED response['Last-Modified'] = http_date( timegm(feedgen.latest_post_date().utctimetuple())) feedgen.write(response, 'utf-8') return response
def sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml'): req_protocol = request.scheme req_site = get_current_site(request) if section is not None: if section not in sitemaps: raise Http404("No sitemap available for section: %r" % section) maps = [sitemaps[section]] else: maps = sitemaps.values() page = request.GET.get("p", 1) urls = [] for site in maps: try: if callable(site): site = site() urls.extend(site.get_urls(page=page, site=req_site, protocol=req_protocol)) except EmptyPage: raise Http404("Page %s empty" % page) except PageNotAnInteger: raise Http404("No page '%s'" % page) response = TemplateResponse(request, template_name, {'urlset': urls}, content_type=content_type) if hasattr(site, 'latest_lastmod'): # if latest_lastmod is defined for site, set header so as # ConditionalGetMiddleware is able to send 304 NOT MODIFIED lastmod = site.latest_lastmod response['Last-Modified'] = http_date( timegm( lastmod.utctimetuple() if isinstance(lastmod, datetime.datetime) else lastmod.timetuple() ) ) return response
def __call__(self, request, *args, **kwargs): try: obj = self.get_object(request, *args, **kwargs) except ObjectDoesNotExist: raise Http404('Feed object does not exist.') feedgen = self.get_feed(obj, request) response = HttpResponse(content_type=feedgen.mime_type) if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'): # if item_pubdate or item_updateddate is defined for the feed, set # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED response['Last-Modified'] = http_date( timegm(feedgen.latest_post_date().utctimetuple())) feedgen.write(response, 'utf-8') return response
def sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml'): req_protocol = request.scheme req_site = get_current_site(request) if section is not None: if section not in sitemaps: raise Http404("No sitemap available for section: %r" % section) maps = [sitemaps[section]] else: maps = list(six.itervalues(sitemaps)) page = request.GET.get("p", 1) urls = [] for site in maps: try: if callable(site): site = site() urls.extend(site.get_urls(page=page, site=req_site, protocol=req_protocol)) except EmptyPage: raise Http404("Page %s empty" % page) except PageNotAnInteger: raise Http404("No page '%s'" % page) response = TemplateResponse(request, template_name, {'urlset': urls}, content_type=content_type) if hasattr(site, 'latest_lastmod'): # if latest_lastmod is defined for site, set header so as # ConditionalGetMiddleware is able to send 304 NOT MODIFIED lastmod = site.latest_lastmod response['Last-Modified'] = http_date( timegm( lastmod.utctimetuple() if isinstance(lastmod, datetime.datetime) else lastmod.timetuple() ) ) return response
def process_response(self, request, response): response['Date'] = http_date() if not response.streaming and not response.has_header('Content-Length'): response['Content-Length'] = str(len(response.content)) # If-None-Match must be ignored if original result would be anything # other than a 2XX or 304 status. 304 status would result in no change. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26 if 200 <= response.status_code < 300 and response.has_header('ETag'): if_none_match = request.META.get('HTTP_IF_NONE_MATCH') if if_none_match == response['ETag']: # Setting the status is enough here. The response handling path # automatically removes content for this status code (in # http.conditional_content_removal()). response.status_code = 304 # If-Modified-Since must be ignored if the original result was not a 200. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25 if response.status_code == 200 and response.has_header('Last-Modified'): if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE') if if_modified_since is not None: if_modified_since = parse_http_date_safe(if_modified_since) if if_modified_since is not None: last_modified = parse_http_date_safe(response['Last-Modified']) if last_modified is not None and last_modified <= if_modified_since: # Setting the status code is enough here (same reasons as # above). response.status_code = 304 return response
def staticfiles(request, file): """ Simple view for serving static files directly from STATICFILES_DIRS. Does not allow subdirectories. Does do If-Modified-Since, though. Based on `django.views.static.serve`. """ if '/..\\' in file: raise Http404 if posixpath.normpath(file) != file: raise Http404 for static_file_dir in settings.STATICFILES_DIRS: fullpath = os.path.abspath(os.path.join(static_file_dir, file)) if not fullpath.startswith(static_file_dir): raise Http404 try: st = os.stat(fullpath) except FileNotFoundError: continue break else: raise Http404 if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), st.st_mtime, st.st_size): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(fullpath) content_type = content_type or 'application/octet-stream' response = FileResponse(open(fullpath, 'rb'), content_type=content_type) response['Last-Modified'] = http_date(st.st_mtime) if stat.S_ISREG(st.st_mode): response['Content-Length'] = st.st_size if encoding: response['Content-Encoding'] = encoding return response
def serve(private_file): # Support If-Last-Modified mtime = private_file.modified_time.timestamp() size = private_file.size if not was_modified_since(private_file.request.META.get('HTTP_IF_MODIFIED_SINCE'), mtime, size): return HttpResponseNotModified() # As of Django 1.8, FileResponse triggers 'wsgi.file_wrapper' in Django's WSGIHandler. # This uses efficient file streaming, such as sendfile() in uWSGI. # When the WSGI container doesn't provide 'wsgi.file_wrapper', it submits the file in 4KB chunks. response = FileResponse(private_file.open()) response['Content-Type'] = private_file.content_type response['Content-Length'] = size response["Last-Modified"] = http_date(mtime) return response
def _image(self, request, pk=None): source = self.get_object() last_modified = int(os.path.getmtime(source.filepath)) response = get_conditional_response(request, last_modified=last_modified) if response is None: response = HttpResponse(open(source.filepath, 'rb'), content_type=mimetypes.guess_type(source.name)[0]) response['Last-Modified'] = http_date(last_modified) return response
def send_file(request, filepath, last_modified=None, filename=None): fullpath = filepath # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if filename: mimetype, encoding = mimetypes.guess_type(filename) else: mimetype, encoding = mimetypes.guess_type(fullpath) mimetype = mimetype or 'application/octet-stream' if settings.USE_SENDFILE: response = django_sendfile_response(request, filepath) else: response = HttpResponse(open(fullpath, 'rb').read(), content_type=mimetype) if not last_modified: response["Last-Modified"] = http_date(statobj.st_mtime) else: if isinstance(last_modified, datetime): last_modified = float(dateformat.format(last_modified, 'U')) response["Last-Modified"] = http_date(epoch_seconds=last_modified) response["Content-Length"] = statobj.st_size if encoding: response["Content-Encoding"] = encoding if filename: filename_escaped = filepath_to_uri(filename) response["Content-Disposition"] = "attachment; filename=%s" % filename_escaped return response
def read(self): response = HttpResponse() full_path = self.get_abs_path().encode('utf-8') if self.quote: full_path = urllib.parse.quote(full_path) response['X-SendFile'] = full_path response['Content-Type'] = mimetypes.guess_type(self.displayname) response['Content-Length'] = self.getcontentlength response['Last-Modified'] = http_date(self.getlastmodified) response['ETag'] = self.getetag raise ResponseException(response)
def read(self): response = HttpResponse() response['X-Accel-Redirect'] = url_join(self.prefix, self.get_path().encode('utf-8')) response['X-Accel-Charset'] = 'utf-8' response['Content-Type'] = mimetypes.guess_type(self.displayname) response['Content-Length'] = self.getcontentlength response['Last-Modified'] = http_date(self.getlastmodified) response['ETag'] = self.getetag raise ResponseException(response)