Python django.http 模块,HttpResponseNotModified() 实例源码

我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用django.http.HttpResponseNotModified()

项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
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
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
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
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
def process_response(self, request, response):
        """
        Calculate the ETag, if needed.
        """
        if settings.USE_ETAGS:
            if response.has_header('ETag'):
                etag = response['ETag']
            elif response.streaming:
                etag = None
            else:
                etag = '"%s"' % hashlib.md5(response.content).hexdigest()
            if etag is not None:
                if (200 <= response.status_code < 300
                        and request.META.get('HTTP_IF_NONE_MATCH') == etag):
                    cookies = response.cookies
                    response = http.HttpResponseNotModified()
                    response.cookies = cookies
                else:
                    response['ETag'] = etag

        return response
项目:trydjango18    作者:lucifer-yqh    | 项目源码 | 文件源码
def process_response(self, request, response):
        """
        Calculate the ETag, if needed.
        """
        if settings.USE_ETAGS:
            if response.has_header('ETag'):
                etag = response['ETag']
            elif response.streaming:
                etag = None
            else:
                etag = '"%s"' % hashlib.md5(response.content).hexdigest()
            if etag is not None:
                if (200 <= response.status_code < 300
                        and request.META.get('HTTP_IF_NONE_MATCH') == etag):
                    cookies = response.cookies
                    response = http.HttpResponseNotModified()
                    response.cookies = cookies
                else:
                    response['ETag'] = etag

        return response
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
def process_response(self, request, response):
        """
        Calculate the ETag, if needed.
        """
        if settings.USE_ETAGS:
            if response.has_header('ETag'):
                etag = response['ETag']
            elif response.streaming:
                etag = None
            else:
                etag = '"%s"' % hashlib.md5(response.content).hexdigest()
            if etag is not None:
                if (200 <= response.status_code < 300
                        and request.META.get('HTTP_IF_NONE_MATCH') == etag):
                    cookies = response.cookies
                    response = http.HttpResponseNotModified()
                    response.cookies = cookies
                else:
                    response['ETag'] = etag

        return response
项目:gougo    作者:amaozhao    | 项目源码 | 文件源码
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
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def _not_modified(request, response=None):
    new_response = HttpResponseNotModified()
    if response:
        # Preserve the headers required by Section 4.1 of RFC 7232, as well as
        # Last-Modified.
        for header in ('Cache-Control', 'Content-Location', 'Date', 'ETag', 'Expires', 'Last-Modified', 'Vary'):
            if header in response:
                new_response[header] = response[header]

        # Preserve cookies as per the cookie specification: "If a proxy server
        # receives a response which contains a Set-cookie header, it should
        # propagate the Set-cookie header to the client, regardless of whether
        # the response was 304 (Not Modified) or 200 (OK).
        # https://curl.haxx.se/rfc/cookie_spec.html
        new_response.cookies = response.cookies
    return new_response
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def process_response(self, request, response):
        """
        Calculate the ETag, if needed.
        """
        if settings.USE_ETAGS:
            if response.has_header('ETag'):
                etag = response['ETag']
            elif response.streaming:
                etag = None
            else:
                etag = '"%s"' % hashlib.md5(response.content).hexdigest()
            if etag is not None:
                if (200 <= response.status_code < 300
                        and request.META.get('HTTP_IF_NONE_MATCH') == etag):
                    cookies = response.cookies
                    response = http.HttpResponseNotModified()
                    response.cookies = cookies
                else:
                    response['ETag'] = etag

        return response
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
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))
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _not_modified(request, response=None):
    if response:
        # We need to keep the cookies, see ticket #4994.
        cookies = response.cookies
        response = HttpResponseNotModified()
        response.cookies = cookies
        return response
    else:
        return HttpResponseNotModified()
项目:borgcube    作者:enkore    | 项目源码 | 文件源码
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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def _not_modified(request, response=None):
    if response:
        # We need to keep the cookies, see ticket #4994.
        cookies = response.cookies
        response = HttpResponseNotModified()
        response.cookies = cookies
        return response
    else:
        return HttpResponseNotModified()
项目:django-private-storage    作者:edoburu    | 项目源码 | 文件源码
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
项目:gougo    作者:amaozhao    | 项目源码 | 文件源码
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))
项目:c3nav    作者:c3nav    | 项目源码 | 文件源码
def sidebar_view(func=None, select_related=None):
    if func is None:
        def wrapped(inner_func):
            return sidebar_view(inner_func, select_related)
        return wrapped

    @wraps(func)
    def with_ajax_check(request, *args, **kwargs):
        request.changeset = ChangeSet.get_for_request(request, select_related)

        ajax = request.is_ajax() or 'ajax' in request.GET

        if not ajax:
            request.META.pop('HTTP_IF_NONE_MATCH', None)

        response = func(request, *args, **kwargs)
        if ajax:
            if isinstance(response, HttpResponseRedirect):
                return render(request, 'editor/redirect.html', {'target': response['location']})
            if not isinstance(response, HttpResponseNotModified):
                response.write(render(request, 'editor/fragment_nav.html', {}).content)
            response['Cache-Control'] = 'no-cache'
            patch_vary_headers(response, ('X-Requested-With', ))
            return response
        if isinstance(response, HttpResponseRedirect):
            return response
        response = render(request, 'editor/map.html', {'content': response.content})
        response['Cache-Control'] = 'no-cache'
        patch_vary_headers(response, ('X-Requested-With', ))
        return response

    return with_ajax_check
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def _not_modified(request, response=None):
    if response:
        # We need to keep the cookies, see ticket #4994.
        cookies = response.cookies
        response = HttpResponseNotModified()
        response.cookies = cookies
        return response
    else:
        return HttpResponseNotModified()
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def _not_modified(request, response=None):
    if response:
        # We need to keep the cookies, see ticket #4994.
        cookies = response.cookies
        response = HttpResponseNotModified()
        response.cookies = cookies
        return response
    else:
        return HttpResponseNotModified()