Python django.http.HttpResponseNotModified() Examples

The following are 14 code examples for showing how to use django.http.HttpResponseNotModified(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: common.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 
Example 2
Project: bioforum   Author: reBiocoder   File: cache.py    License: MIT License 6 votes vote down vote up
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 
Example 3
Project: django-private-storage   Author: edoburu   File: servers.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 4
Project: django-private-storage   Author: edoburu   File: servers.py    License: Apache License 2.0 6 votes vote down vote up
def serve(private_file):
        # This supports If-Modified-Since and sends the file in 4KB chunks
        try:
            full_path = private_file.full_path
        except NotImplementedError:
            # S3 files, fall back to streaming server
            return DjangoStreamingServer.serve(private_file)
        else:
            # Using Django's serve gives If-Modified-Since support out of the box.
            response = serve(private_file.request, full_path, document_root='/', show_indexes=False)
            if private_file.request.method == 'HEAD' and response.status_code == 200:
                # Avoid reading the file at all, copy FileResponse headers
                # This is not needed for HttpResponseNotModified(), hence the 200 code check
                head_response = HttpResponse(status=response.status_code)
                for header, value in response.items():
                    head_response[header] = value
                return head_response
            else:
                return response 
Example 5
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: cache.py    License: MIT License 6 votes vote down vote up
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 
Example 6
Project: python   Author: Yeah-Kun   File: cache.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 7
Project: python2017   Author: bpgc-cte   File: cache.py    License: MIT License 6 votes vote down vote up
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 
Example 8
Project: django-sendfile2   Author: moggers87   File: simple.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 9
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 
Example 10
Project: luscan-devel   Author: blackye   File: common.py    License: GNU General Public License v2.0 5 votes vote down vote up
def process_response(self, request, response):
        "Send broken link emails and calculate the Etag, if needed."
        if response.status_code == 404:
            if settings.SEND_BROKEN_LINK_EMAILS and not settings.DEBUG:
                # If the referrer was from an internal link or a non-search-engine site,
                # send a note to the managers.
                domain = request.get_host()
                referer = request.META.get('HTTP_REFERER', None)
                is_internal = _is_internal_request(domain, referer)
                path = request.get_full_path()
                if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer):
                    ua = request.META.get('HTTP_USER_AGENT', '<none>')
                    ip = request.META.get('REMOTE_ADDR', '<none>')
                    mail_managers("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain),
                        "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" \
                                  % (referer, request.get_full_path(), ua, ip),
                                  fail_silently=True)
                return response

        # Use ETags, if requested.
        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 
Example 11
Project: openhgsenti   Author: drexly   File: cache.py    License: Apache License 2.0 5 votes vote down vote up
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() 
Example 12
Project: djongo   Author: nesdis   File: test_static.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_modified_since(self):
        file_name = 'file.txt'
        response = self.client.get(
            '/%s/%s' % (self.prefix, file_name),
            HTTP_IF_MODIFIED_SINCE='Mon, 18 Jan 2038 05:14:07 GMT'
            # This is 24h before max Unix time. Remember to fix Django and
            # update this test well before 2038 :)
        )
        self.assertIsInstance(response, HttpResponseNotModified) 
Example 13
Project: djongo   Author: nesdis   File: test_static.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_modified_since(self):
        file_name = 'file.txt'
        response = self.client.get(
            '/%s/%s' % (self.prefix, file_name),
            HTTP_IF_MODIFIED_SINCE='Mon, 18 Jan 2038 05:14:07 GMT'
            # This is 24h before max Unix time. Remember to fix Django and
            # update this test well before 2038 :)
        )
        self.assertIsInstance(response, HttpResponseNotModified) 
Example 14
Project: c3nav   Author: c3nav   File: base.py    License: Apache License 2.0 4 votes vote down vote up
def sidebar_view(func=None, select_related=None, api_hybrid=False):
    if func is None:
        def wrapped(inner_func):
            return sidebar_view(inner_func, select_related=select_related, api_hybrid=api_hybrid)
        return wrapped

    @wraps(func)
    def wrapped(request, *args, api=False, **kwargs):
        if api and not api_hybrid:
            raise Exception('API call on a view without api_hybrid!')

        if not can_access_editor(request):
            raise PermissionDenied

        request.changeset = ChangeSet.get_for_request(request, select_related)

        if api:
            request.is_delete = request.method == 'DELETE'
            return call_api_hybrid_view_for_api(func, request, *args, **kwargs)

        ajax = request.is_ajax() or 'ajax' in request.GET
        if not ajax:
            request.META.pop('HTTP_IF_NONE_MATCH', None)

        if api_hybrid:
            response = call_api_hybrid_view_for_html(func, request, *args, **kwargs)
        else:
            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)
                if request.mobileclient:
                    response.write(render(request, 'editor/fragment_mobileclientdata.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.decode()})
        response['Cache-Control'] = 'no-cache'
        patch_vary_headers(response, ('X-Requested-With', ))
        return response

    wrapped.api_hybrid = api_hybrid

    return wrapped