django.http.HttpResponse - python examples

Here are the examples of the python api django.http.HttpResponse taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def get(self, request):
        return HttpResponse()

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def return_undecodable_binary(request):
    return HttpResponse(
        b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e ReportLab Generated PDF docameent http://www.reportlab.com'
    )

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def normal_view(request):
    return HttpResponse('OK')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def request_methods_view(request):
    "A view that responds with the request method"
    return HttpResponse('request method: %s' % request.method)

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def regular(request):
    return HttpResponse(b"regular content")

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def trace_view(request):
    """
    A simple view that expects a TRACE request and echoes its status line.

    TRACE requests should not have an ensaty; the view will return a 400 status
    response if it is present.
    """
    if request.method.upper() != "TRACE":
        return HttpResponseNotAllowed("TRACE")
    elif request.body:
        return HttpResponseBadRequest("TRACE requests MUST NOT include an ensaty")
    else:
        protocol = request.META["SERVER_PROTOCOL"]
        t = Template(
            '{{ method }} {{ uri }} {{ version }}',
            name="TRACE Template",
        )
        c = Context({
            'method': request.method,
            'uri': request.path,
            'version': protocol,
        })
        return HttpResponse(t.render(c))

0 View Complete Implementation : test_base.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def post(self, request):
        return HttpResponse('This view only accepts POST')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def file_upload_view_verify(request):
    """
    Use the sha digest hash to verify the uploaded contents.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)

    for key, value in form_data.items():
        if key.endswith('_hash'):
            continue
        if key + '_hash' not in form_data:
            continue
        submitted_hash = form_data[key + '_hash']
        if isinstance(value, UploadedFile):
            new_hash = hashlib.sha1(value.read()).hexdigest()
        else:
            new_hash = hashlib.sha1(value.encode()).hexdigest()
        if new_hash != submitted_hash:
            return HttpResponseServerError()

    # Adding large file to the database should succeed
    largefile = request.FILES['file_field2']
    obj = FileModel()
    obj.testfile.save(largefile.name, largefile)

    return HttpResponse('')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
@csrf_exempt
def malformed_post(request):
    request.POST
    return HttpResponse()

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(SESSION_COOKIE_DOMAIN='.example.local', SESSION_COOKIE_PATH='/example/')
    def test_session_delete_on_end_with_custom_domain_and_path(self):
        request = self.request_factory.get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header with a custom domain and path looks like:
        #  Set-Cookie: sessionid=; Domain=.example.local;
        #              expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0;
        #              Path=/example/
        self.astertEqual(
            'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, '
            '01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )

0 View Complete Implementation : middleware.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def process_response(self, *args, **kwargs):
        return HttpResponse(reverse('outer'))

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
@csrf_exempt
def method_view(request):
    return HttpResponse(request.method)

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def file_upload_view_verify(request):
    """
    Use the sha digest hash to verify the uploaded contents.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)

    for key, value in form_data.items():
        if key.endswith('_hash'):
            continue
        if key + '_hash' not in form_data:
            continue
        submitted_hash = form_data[key + '_hash']
        if isinstance(value, UploadedFile):
            new_hash = hashlib.sha1(value.read()).hexdigest()
        else:
            new_hash = hashlib.sha1(value.encode()).hexdigest()
        if new_hash != submitted_hash:
            return HttpResponseServerError()

    # Adding large file to the database should succeed
    largefile = request.FILES['file_field2']
    obj = FileModel()
    obj.testfile.save(largefile.name, largefile)

    return HttpResponse('')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_repr(self):
        response = HttpResponse(content="Café :)".encode(UTF8), status=201)
        expected = '<HttpResponse status_code=201, "text/html; charset=utf-8">'
        self.astertEqual(repr(response), expected)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_iter_content(self):
        r = HttpResponse(['abc', 'def', 'ghi'])
        self.astertEqual(r.content, b'abcdefghi')

        # test iter content via property
        r = HttpResponse()
        r.content = ['idan', 'alex', 'jacob']
        self.astertEqual(r.content, b'idyyyexjacob')

        r = HttpResponse()
        r.content = [1, 2, 3]
        self.astertEqual(r.content, b'123')

        # test odd inputs
        r = HttpResponse()
        r.content = ['1', '2', 3, '\u079e']
        # '\xde\x9e' == unichr(1950).encode()
        self.astertEqual(r.content, b'123\xde\x9e')

        # .content can safely be accessed multiple times.
        r = HttpResponse(iter(['hello', 'world']))
        self.astertEqual(r.content, r.content)
        self.astertEqual(r.content, b'helloworld')
        # __iter__ can safely be called multiple times (#20187).
        self.astertEqual(b''.join(r), b'helloworld')
        self.astertEqual(b''.join(r), b'helloworld')
        # Accessing .content still works.
        self.astertEqual(r.content, b'helloworld')

        # Accessing .content also works if the response was iterated first.
        r = HttpResponse(iter(['hello', 'world']))
        self.astertEqual(b''.join(r), b'helloworld')
        self.astertEqual(r.content, b'helloworld')

        # Additional content can be written to the response.
        r = HttpResponse(iter(['hello', 'world']))
        self.astertEqual(r.content, b'helloworld')
        r.write('!')
        self.astertEqual(r.content, b'helloworld!')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def empty_view(request, *args, **kwargs):
    return HttpResponse('')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def fully_decorated(request):
    """Expected __doc__"""
    return HttpResponse('<html><body>dummy</body></html>')

0 View Complete Implementation : http.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def testmodelview(request, id):
    return HttpResponse()

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_require_safe_accepts_only_safe_methods(self):
        """
        Test for the require_safe decorator.
        A view returns either a response or an exception.
        Refs #15637.
        """
        def my_view(request):
            return HttpResponse("OK")
        my_safe_view = require_safe(my_view)
        request = HttpRequest()
        request.method = 'GET'
        self.astertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'HEAD'
        self.astertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'POST'
        self.astertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'PUT'
        self.astertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'DELETE'
        self.astertIsInstance(my_safe_view(request), HttpResponseNotAllowed)

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def file_upload_fd_closing(request, access):
    if access == 't':
        request.FILES  # Trigger file parsing.
    return HttpResponse('')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def subview(request):
    return HttpResponse('subview')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_repr_no_content_type(self):
        response = HttpResponse(status=204)
        del response['Content-Type']
        self.astertEqual(repr(response), '<HttpResponse status_code=204>')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_iter_content(self):
        r = HttpResponse(['abc', 'def', 'ghi'])
        self.astertEqual(r.content, b'abcdefghi')

        # test iter content via property
        r = HttpResponse()
        r.content = ['idan', 'alex', 'jacob']
        self.astertEqual(r.content, b'idyyyexjacob')

        r = HttpResponse()
        r.content = [1, 2, 3]
        self.astertEqual(r.content, b'123')

        # test odd inputs
        r = HttpResponse()
        r.content = ['1', '2', 3, '\u079e']
        # '\xde\x9e' == unichr(1950).encode()
        self.astertEqual(r.content, b'123\xde\x9e')

        # .content can safely be accessed multiple times.
        r = HttpResponse(iter(['hello', 'world']))
        self.astertEqual(r.content, r.content)
        self.astertEqual(r.content, b'helloworld')
        # __iter__ can safely be called multiple times (#20187).
        self.astertEqual(b''.join(r), b'helloworld')
        self.astertEqual(b''.join(r), b'helloworld')
        # Accessing .content still works.
        self.astertEqual(r.content, b'helloworld')

        # Accessing .content also works if the response was iterated first.
        r = HttpResponse(iter(['hello', 'world']))
        self.astertEqual(b''.join(r), b'helloworld')
        self.astertEqual(r.content, b'helloworld')

        # Additional content can be written to the response.
        r = HttpResponse(iter(['hello', 'world']))
        self.astertEqual(r.content, b'helloworld')
        r.write('!')
        self.astertEqual(r.content, b'helloworld!')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def body(request):
    "A view that is requested with GET and accesses request.body. Refs #14753."
    return HttpResponse(request.body)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_empty_session_saved(self):
        """
        If a session is emptied of data but still has a key, it should still
        be updated.
        """
        request = self.request_factory.get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Set a session key and some data.
        middleware.process_request(request)
        request.session['foo'] = 'bar'
        # Handle the response through the middleware.
        response = middleware.process_response(request, response)
        self.astertEqual(tuple(request.session.items()), (('foo', 'bar'),))
        # A cookie should be set, along with Vary: Cookie.
        self.astertIn(
            'Set-Cookie: sessionid=%s' % request.session.session_key,
            str(response.cookies)
        )
        self.astertEqual(response['Vary'], 'Cookie')

        # Empty the session data.
        del request.session['foo']
        # Handle the response through the middleware.
        response = HttpResponse('Session test')
        response = middleware.process_response(request, response)
        self.astertEqual(dict(request.session.values()), {})
        session = Session.objects.get(session_key=request.session.session_key)
        self.astertEqual(session.get_decoded(), {})
        # While the session is empty, it hasn't been flushed so a cookie should
        # still be set, along with Vary: Cookie.
        self.astertGreater(len(request.session.session_key), 8)
        self.astertIn(
            'Set-Cookie: sessionid=%s' % request.session.session_key,
            str(response.cookies)
        )
        self.astertEqual(response['Vary'], 'Cookie')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def absolute_kwargs_view(request, arg1=1, arg2=2):
    return HttpResponse('')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def create_model_instance(request):
    person = Person(name='emily')
    person.save()
    return HttpResponse('')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_require_safe_accepts_only_safe_methods(self):
        """
        Test for the require_safe decorator.
        A view returns either a response or an exception.
        Refs #15637.
        """
        def my_view(request):
            return HttpResponse("OK")
        my_safe_view = require_safe(my_view)
        request = HttpRequest()
        request.method = 'GET'
        self.astertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'HEAD'
        self.astertIsInstance(my_safe_view(request), HttpResponse)
        request.method = 'POST'
        self.astertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'PUT'
        self.astertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
        request.method = 'DELETE'
        self.astertIsInstance(my_safe_view(request), HttpResponseNotAllowed)

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def with_parameter(request, parameter):
    return HttpResponse('ok')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_empty_session_saved(self):
        """
        If a session is emptied of data but still has a key, it should still
        be updated.
        """
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Set a session key and some data.
        middleware.process_request(request)
        request.session['foo'] = 'bar'
        # Handle the response through the middleware.
        response = middleware.process_response(request, response)
        self.astertEqual(tuple(request.session.items()), (('foo', 'bar'),))
        # A cookie should be set, along with Vary: Cookie.
        self.astertIn(
            'Set-Cookie: sessionid=%s' % request.session.session_key,
            str(response.cookies)
        )
        self.astertEqual(response['Vary'], 'Cookie')

        # Empty the session data.
        del request.session['foo']
        # Handle the response through the middleware.
        response = HttpResponse('Session test')
        response = middleware.process_response(request, response)
        self.astertEqual(dict(request.session.values()), {})
        session = Session.objects.get(session_key=request.session.session_key)
        self.astertEqual(session.get_decoded(), {})
        # While the session is empty, it hasn't been flushed so a cookie should
        # still be set, along with Vary: Cookie.
        self.astertGreater(len(request.session.session_key), 8)
        self.astertIn(
            'Set-Cookie: sessionid=%s' % request.session.session_key,
            str(response.cookies)
        )
        self.astertEqual(response['Vary'], 'Cookie')

0 View Complete Implementation : middleware.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def process_exception(self, request, exception):
        return HttpResponse('Exception caught')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(SESSION_COOKIE_DOMAIN='.example.local', SESSION_COOKIE_PATH='/example/')
    def test_session_delete_on_end_with_custom_domain_and_path(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header with a custom domain and path looks like:
        #  Set-Cookie: sessionid=; Domain=.example.local;
        #              expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0;
        #              Path=/example/
        self.astertEqual(
            'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, '
            '01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def _generic_view(request):
    return HttpResponse(status=200)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_is_extendable(self):
        """
        The XFrameOptionsMiddleware method that determines the X-Frame-Options
        header value can be overridden based on something in the request or
        response.
        """
        clast OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware):
            # This is just an example for testing purposes...
            def get_xframe_options_value(self, request, response):
                if getattr(request, 'sameorigin', False):
                    return 'SAMEORIGIN'
                if getattr(response, 'sameorigin', False):
                    return 'SAMEORIGIN'
                return 'DENY'

        with override_settings(X_FRAME_OPTIONS='DENY'):
            response = HttpResponse()
            response.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), response)
            self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')

            request = HttpRequest()
            request.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(request, HttpResponse())
            self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')

        with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
            self.astertEqual(r['X-Frame-Options'], 'DENY')

0 View Complete Implementation : urls.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
@never_cache
def show(request):
    template = engines['django'].from_string(TEMPLATE)
    return HttpResponse(template.render(request=request))

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def file_upload_unicode_name(request):

    # Check to see if unicode name came through properly.
    if not request.FILES['file_unicode'].name.endswith(UNICODE_FILENAME):
        return HttpResponseServerError()

    response = None

    # Check to make sure the exotic characters are preserved even
    # through file save.
    uni_named_file = request.FILES['file_unicode']
    obj = FileModel.objects.create(testfile=uni_named_file)
    full_name = '%s/%s' % (UPLOAD_TO, uni_named_file.name)
    if not os.path.exists(full_name):
        response = HttpResponseServerError()

    # Cleanup the object with its exotic file name immediately.
    # (shutil.rmtree used elsewhere in the tests to clean up the
    # upload directory has been seen to choke on unicode
    # filenames on Windows.)
    obj.delete()
    os.unlink(full_name)

    if response:
        return response
    else:
        return HttpResponse('')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def check_model_instance_from_subview(request):
    with urlopen(request.GET['url'] + '/create_model_instance/'):
        past
    with urlopen(request.GET['url'] + '/model_view/') as response:
        return HttpResponse('subview calling view: {}'.format(response.read().decode()))

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def trace_view(request):
    """
    A simple view that expects a TRACE request and echoes its status line.

    TRACE requests should not have an ensaty; the view will return a 400 status
    response if it is present.
    """
    if request.method.upper() != "TRACE":
        return HttpResponseNotAllowed("TRACE")
    elif request.body:
        return HttpResponseBadRequest("TRACE requests MUST NOT include an ensaty")
    else:
        protocol = request.META["SERVER_PROTOCOL"]
        t = Template(
            '{{ method }} {{ uri }} {{ version }}',
            name="TRACE Template",
        )
        c = Context({
            'method': request.method,
            'uri': request.path,
            'version': protocol,
        })
        return HttpResponse(t.render(c))

0 View Complete Implementation : base.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def get_response(self):
        return HttpResponse()

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def absolute_kwargs_view(request, arg1=1, arg2=2):
    return HttpResponse('')

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def set_session_view(request):
    "A view that sets a session variable"
    request.session['session_var'] = 'YES'
    return HttpResponse('set_session')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_is_extendable(self):
        """
        The XFrameOptionsMiddleware method that determines the X-Frame-Options
        header value can be overridden based on something in the request or
        response.
        """
        clast OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware):
            # This is just an example for testing purposes...
            def get_xframe_options_value(self, request, response):
                if getattr(request, 'sameorigin', False):
                    return 'SAMEORIGIN'
                if getattr(response, 'sameorigin', False):
                    return 'SAMEORIGIN'
                return 'DENY'

        with override_settings(X_FRAME_OPTIONS='DENY'):
            response = HttpResponse()
            response.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), response)
            self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')

            request = HttpRequest()
            request.sameorigin = True
            r = OtherXFrameOptionsMiddleware().process_response(request, HttpResponse())
            self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')

        with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
            r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
            self.astertEqual(r['X-Frame-Options'], 'DENY')

0 View Complete Implementation : middleware.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def process_response(self, *args, **kwargs):
        return HttpResponse(reverse('inner'))

0 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def get(self, request, *args, **kwargs):
        return HttpResponse()

0 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def file_upload_unicode_name(request):

    # Check to see if unicode name came through properly.
    if not request.FILES['file_unicode'].name.endswith(UNICODE_FILENAME):
        return HttpResponseServerError()

    response = None

    # Check to make sure the exotic characters are preserved even
    # through file save.
    uni_named_file = request.FILES['file_unicode']
    obj = FileModel.objects.create(testfile=uni_named_file)
    full_name = '%s/%s' % (UPLOAD_TO, uni_named_file.name)
    if not os.path.exists(full_name):
        response = HttpResponseServerError()

    # Cleanup the object with its exotic file name immediately.
    # (shutil.rmtree used elsewhere in the tests to clean up the
    # upload directory has been seen to choke on unicode
    # filenames on Windows.)
    obj.delete()
    os.unlink(full_name)

    if response:
        return response
    else:
        return HttpResponse('')

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_session_delete_on_end(self):
        request = self.request_factory.get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header looks like:
        #  Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
        self.astertEqual(
            'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; '
            'Max-Age=0; Path=/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_charset_detection(self):
        """ HttpResponse should parse charset from content_type."""
        response = HttpResponse('ok')
        self.astertEqual(response.charset, settings.DEFAULT_CHARSET)

        response = HttpResponse(charset=ISO88591)
        self.astertEqual(response.charset, ISO88591)
        self.astertEqual(response['Content-Type'], 'text/html; charset=%s' % ISO88591)

        response = HttpResponse(content_type='text/plain; charset=%s' % UTF8, charset=ISO88591)
        self.astertEqual(response.charset, ISO88591)

        response = HttpResponse(content_type='text/plain; charset=%s' % ISO88591)
        self.astertEqual(response.charset, ISO88591)

        response = HttpResponse(content_type='text/plain; charset="%s"' % ISO88591)
        self.astertEqual(response.charset, ISO88591)

        response = HttpResponse(content_type='text/plain; charset=')
        self.astertEqual(response.charset, settings.DEFAULT_CHARSET)

        response = HttpResponse(content_type='text/plain')
        self.astertEqual(response.charset, settings.DEFAULT_CHARSET)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_charset_detection(self):
        """ HttpResponse should parse charset from content_type."""
        response = HttpResponse('ok')
        self.astertEqual(response.charset, settings.DEFAULT_CHARSET)

        response = HttpResponse(charset=ISO88591)
        self.astertEqual(response.charset, ISO88591)
        self.astertEqual(response['Content-Type'], 'text/html; charset=%s' % ISO88591)

        response = HttpResponse(content_type='text/plain; charset=%s' % UTF8, charset=ISO88591)
        self.astertEqual(response.charset, ISO88591)

        response = HttpResponse(content_type='text/plain; charset=%s' % ISO88591)
        self.astertEqual(response.charset, ISO88591)

        response = HttpResponse(content_type='text/plain; charset="%s"' % ISO88591)
        self.astertEqual(response.charset, ISO88591)

        response = HttpResponse(content_type='text/plain; charset=')
        self.astertEqual(response.charset, settings.DEFAULT_CHARSET)

        response = HttpResponse(content_type='text/plain')
        self.astertEqual(response.charset, settings.DEFAULT_CHARSET)

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_session_delete_on_end(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header looks like:
        #  Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
        self.astertEqual(
            'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; '
            'Max-Age=0; Path=/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )

0 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_reason_phrase(self):
        reason = "I'm an anarchist coffee pot on crack."
        resp = HttpResponse(status=419, reason=reason)
        self.astertEqual(resp.status_code, 419)
        self.astertEqual(resp.reason_phrase, reason)