本文整理汇总了Python中django.utils.http.http_date方法的典型用法代码示例。如果您正苦于以下问题:Python http.http_date方法的具体用法?Python http.http_date怎么用?Python http.http_date使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.http
的用法示例。
在下文中一共展示了http.http_date方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: patch_response_headers
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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)
示例2: get
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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
示例3: serve
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
def serve(private_file):
# Support If-Last-Modified
if sys.version_info >= (3,):
mtime = private_file.modified_time.timestamp()
else:
mtime = time.mktime(private_file.modified_time.timetuple())
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.
if private_file.request.method == 'HEAD':
# Avoid reading the file at all
response = HttpResponse()
else:
response = FileResponse(private_file.open())
response['Content-Type'] = private_file.content_type
response['Content-Length'] = size
response["Last-Modified"] = http_date(mtime)
return response
示例4: process_response
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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 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 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
示例5: patch_response_headers
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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)
示例6: process_response
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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
示例7: sendfile
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
def sendfile(request, filepath, **kwargs):
'''Use the SENDFILE_ROOT value composed with the path arrived as argument
to build an absolute path with which resolve and return the file contents.
If the path points to a file out of the root directory (should cover both
situations with '..' and symlinks) then a 404 is raised.
'''
statobj = filepath.stat()
# Respect the If-Modified-Since header.
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj.st_mtime, statobj.st_size):
return HttpResponseNotModified()
with File(filepath.open('rb')) as f:
response = HttpResponse(f.chunks())
response["Last-Modified"] = http_date(statobj.st_mtime)
return response
示例8: process_response
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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
示例9: __call__
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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
示例10: sitemap
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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
示例11: serve
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
def serve(request, path, document_root=None, show_indexes=False):
"""
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
from django.views.static import serve
url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
of the directory. This index view will use the template hardcoded below,
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(path).lstrip('/')
fullpath = safe_join(document_root, path)
if os.path.isdir(fullpath):
if show_indexes:
return directory_index(path, fullpath)
raise Http404(_("Directory indexes are not allowed here."))
if not os.path.exists(fullpath):
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj.st_mtime, statobj.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(statobj.st_mtime)
if stat.S_ISREG(statobj.st_mode):
response["Content-Length"] = statobj.st_size
if encoding:
response["Content-Encoding"] = encoding
return response
示例12: __call__
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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
示例13: __call__
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
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="text/calendar, text/x-vcalendar, application/hbs-vcs"
)
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
示例14: serve
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
def serve(request, path, document_root=None, show_indexes=False):
"""
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
from django.views.static import serve
url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
of the directory. This index view will use the template hardcoded below,
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(path).lstrip('/')
fullpath = Path(safe_join(document_root, path))
if fullpath.is_dir():
if show_indexes:
return directory_index(path, fullpath)
raise Http404(_("Directory indexes are not allowed here."))
if not fullpath.exists():
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
# Respect the If-Modified-Since header.
statobj = fullpath.stat()
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj.st_mtime, statobj.st_size):
return HttpResponseNotModified()
content_type, encoding = mimetypes.guess_type(str(fullpath))
content_type = content_type or 'application/octet-stream'
response = FileResponse(fullpath.open('rb'), content_type=content_type)
response["Last-Modified"] = http_date(statobj.st_mtime)
if encoding:
response["Content-Encoding"] = encoding
return response
示例15: sendfile
# 需要导入模块: from django.utils import http [as 别名]
# 或者: from django.utils.http import http_date [as 别名]
def sendfile(request, filename, **kwargs):
# Respect the If-Modified-Since header.
statobj = os.stat(filename)
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
return HttpResponseNotModified()
response = StreamingHttpResponse(FileWrapper(open(filename, 'rb')))
response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
return response