Python django.core.handlers.wsgi.WSGIHandler() Examples

The following are 30 code examples of django.core.handlers.wsgi.WSGIHandler(). 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 also want to check out all available functions/classes of the module django.core.handlers.wsgi , or try the search function .
Example #1
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_response_is_in_retry_context_in_transaction(self):
        handler = views.WebApplicationHandler(2)

        def check_retry_context_active(request):
            self.assertThat(retry_context.active, Is(True))

        get_response = self.patch(WSGIHandler, "get_response")
        get_response.side_effect = check_retry_context_active

        request = make_request()
        request.path = factory.make_name("path")

        self.assertThat(retry_context.active, Is(False))
        handler.get_response(request)
        self.assertThat(retry_context.active, Is(False))
        self.assertThat(get_response, MockCalledOnceWith(request)) 
Example #2
Source File: testcases.py    From bioforum with MIT License 6 votes vote down vote up
def run(self):
        """
        Set up the live server and databases, and then loop over handling
        HTTP requests.
        """
        if self.connections_override:
            # Override this thread's database connections with the ones
            # provided by the main thread.
            for alias, conn in self.connections_override.items():
                connections[alias] = conn
        try:
            # Create the handler for serving static and media files
            handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))
            self.httpd = self._create_server()
            # If binding to port zero, assign the port allocated by the OS.
            if self.port == 0:
                self.port = self.httpd.server_address[1]
            self.httpd.set_app(handler)
            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set()
        finally:
            connections.close_all() 
Example #3
Source File: offline.py    From ara with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        """
        Set up the live server and databases, and then loop over handling
        HTTP requests.
        """
        try:
            # Create the handler for serving static and media files
            self.httpd = self._create_server()
            # If binding to port zero, assign the port allocated by the OS.
            if self.port == 0:
                self.port = self.httpd.server_address[1]
            self.httpd.set_app(WSGIHandler())
            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set() 
Example #4
Source File: testcases.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def run(self):
        """
        Set up the live server and databases, and then loop over handling
        HTTP requests.
        """
        if self.connections_override:
            # Override this thread's database connections with the ones
            # provided by the main thread.
            for alias, conn in self.connections_override.items():
                connections[alias] = conn
        try:
            # Create the handler for serving static and media files
            handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))
            self.httpd = self._create_server()
            # If binding to port zero, assign the port allocated by the OS.
            if self.port == 0:
                self.port = self.httpd.server_address[1]
            self.httpd.set_app(handler)
            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set()
        finally:
            connections.close_all() 
Example #5
Source File: testcases.py    From python with Apache License 2.0 6 votes vote down vote up
def run(self):
        """
        Sets up the live server and databases, and then loops over handling
        http requests.
        """
        if self.connections_override:
            # Override this thread's database connections with the ones
            # provided by the main thread.
            for alias, conn in self.connections_override.items():
                connections[alias] = conn
        try:
            # Create the handler for serving static and media files
            handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))
            self.httpd = self._create_server()
            # If binding to port zero, assign the port allocated by the OS.
            if self.port == 0:
                self.port = self.httpd.server_address[1]
            self.httpd.set_app(handler)
            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set()
        finally:
            connections.close_all() 
Example #6
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_response_sends_signal_on_deadlock_failures(self):
        get_response = self.patch(WSGIHandler, "get_response")
        get_response.side_effect = make_deadlock_failure()

        send_request_exception = self.patch_autospec(
            signals.got_request_exception, "send"
        )

        handler = views.WebApplicationHandler(1)
        request = make_request()
        request.path = factory.make_name("path")
        handler.get_response(request)

        self.assertThat(
            send_request_exception,
            MockCalledOnceWith(
                sender=views.WebApplicationHandler, request=request
            ),
        ) 
Example #7
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_response_sends_signal_on_serialization_failures(self):
        get_response = self.patch(WSGIHandler, "get_response")
        get_response.side_effect = (
            lambda request: self.cause_serialization_failure()
        )

        send_request_exception = self.patch_autospec(
            signals.got_request_exception, "send"
        )

        handler = views.WebApplicationHandler(1)
        request = make_request()
        request.path = factory.make_name("path")
        handler.get_response(request)

        self.assertThat(
            send_request_exception,
            MockCalledOnceWith(
                sender=views.WebApplicationHandler, request=request
            ),
        ) 
Example #8
Source File: testcases.py    From python2017 with MIT License 6 votes vote down vote up
def run(self):
        """
        Sets up the live server and databases, and then loops over handling
        http requests.
        """
        if self.connections_override:
            # Override this thread's database connections with the ones
            # provided by the main thread.
            for alias, conn in self.connections_override.items():
                connections[alias] = conn
        try:
            # Create the handler for serving static and media files
            handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))
            self.httpd = self._create_server()
            # If binding to port zero, assign the port allocated by the OS.
            if self.port == 0:
                self.port = self.httpd.server_address[1]
            self.httpd.set_app(handler)
            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set()
        finally:
            connections.close_all() 
Example #9
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_response_tries_only_once(self):
        response = HttpResponse(status=200)
        get_response = self.patch(WSGIHandler, "get_response")
        get_response.return_value = response

        handler = views.WebApplicationHandler()
        request = make_request()
        request.path = factory.make_name("path")
        observed_response = handler.get_response(request)

        self.assertThat(get_response, MockCalledOnceWith(request))
        self.assertThat(observed_response, Is(response)) 
Example #10
Source File: test_exception.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_data_upload_max_memory_size_exceeded(self):
        response = WSGIHandler()(self.get_suspicious_environ(), lambda *a, **k: None)
        self.assertEqual(response.status_code, 400) 
Example #11
Source File: test_exception.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_data_upload_max_number_fields_exceeded(self):
        response = WSGIHandler()(self.get_suspicious_environ(), lambda *a, **k: None)
        self.assertEqual(response.status_code, 400) 
Example #12
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_middleware_initialized(self):
        handler = WSGIHandler()
        self.assertIsNotNone(handler._middleware_chain) 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_bad_path_info(self):
        """
        A non-UTF-8 path populates PATH_INFO with an URL-encoded path and
        produces a 404.
        """
        environ = self.request_factory.get('/').environ
        environ['PATH_INFO'] = '\xed'
        handler = WSGIHandler()
        response = handler(environ, lambda *a, **k: None)
        # The path of the request will be encoded to '/%ED'.
        self.assertEqual(response.status_code, 404) 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_multipart_boundary(self):
        """
        Invalid boundary string should produce a "Bad Request" response, not a
        server error (#23887).
        """
        environ = self.request_factory.post('/malformed_post/').environ
        environ['CONTENT_TYPE'] = 'multipart/form-data; boundary=WRONG\x07'
        handler = WSGIHandler()
        response = handler(environ, lambda *a, **k: None)
        # Expect "bad request" response
        self.assertEqual(response.status_code, 400) 
Example #15
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_response_catches_serialization_failures(self):
        get_response = self.patch(WSGIHandler, "get_response")
        get_response.side_effect = (
            lambda request: self.cause_serialization_failure()
        )

        handler = views.WebApplicationHandler(1)
        request = make_request()
        request.path = factory.make_name("path")
        response = handler.get_response(request)

        self.assertThat(get_response, MockCalledOnceWith(request))
        self.assertThat(response, IsInstance(HttpResponseConflict)) 
Example #16
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_response_catches_deadlock_failures(self):
        get_response = self.patch(WSGIHandler, "get_response")
        get_response.side_effect = make_deadlock_failure()

        handler = views.WebApplicationHandler(1)
        request = make_request()
        request.path = factory.make_name("path")
        response = handler.get_response(request)

        self.assertThat(get_response, MockCalledOnceWith(request))
        self.assertThat(response, IsInstance(HttpResponseConflict)) 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_middleware_initialized(self):
        handler = WSGIHandler()
        self.assertIsNotNone(handler._middleware_chain) 
Example #18
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_response_logs_retry_and_resets_request(self):
        timeout = 1.0 + (random() * 99)
        handler = views.WebApplicationHandler(2, timeout)

        def set_retry(request):
            response = HttpResponse(status=200)
            handler._WebApplicationHandler__retry.add(response)
            return response

        get_response = self.patch(WSGIHandler, "get_response")
        get_response.side_effect = set_retry

        self.patch_autospec(views, "log_failed_attempt")
        self.patch_autospec(views, "log_final_failed_attempt")
        reset_request = self.patch_autospec(views, "reset_request")
        reset_request.side_effect = lambda request: request

        request = make_request()
        request.path = factory.make_name("path")
        handler.get_response(request)

        self.expectThat(
            views.log_failed_attempt,
            MockCalledOnceWith(request, 1, ANY, ANY, ANY),
        )
        self.expectThat(
            views.log_final_failed_attempt, MockCalledOnceWith(request, 2, ANY)
        )
        self.expectThat(reset_request, MockCalledOnceWith(request)) 
Example #19
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_response_up_calls_in_transaction(self):
        handler = views.WebApplicationHandler(2)

        def check_in_transaction(request):
            validate_in_transaction(connection)

        get_response = self.patch(WSGIHandler, "get_response")
        get_response.side_effect = check_in_transaction

        request = make_request()
        request.path = factory.make_name("path")
        handler.get_response(request)

        self.assertThat(get_response, MockCalledOnceWith(request)) 
Example #20
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_response_restores_files_across_requests(self):
        handler = views.WebApplicationHandler(3)
        file_content = sample_binary_data
        file_name = "content"

        recorder = []

        def get_response_read_content_files(self, request):
            # Simple get_response method which returns the 'file_name' file
            # from the request in the response.
            content = request.FILES[file_name].read()
            # Record calls.
            recorder.append(content)
            response = HttpResponse(
                content=content,
                status=200,
                content_type=b"text/plain; charset=utf-8",
            )
            handler._WebApplicationHandler__retry.add(response)
            return response

        self.patch(
            WSGIHandler, "get_response", get_response_read_content_files
        )

        body, headers = encode_multipart_data(
            [], [[file_name, io.BytesIO(file_content)]]
        )
        env = {
            "REQUEST_METHOD": "POST",
            "wsgi.input": wsgi._InputStream(io.BytesIO(body.encode("utf-8"))),
            "CONTENT_TYPE": headers["Content-Type"],
            "CONTENT_LENGTH": headers["Content-Length"],
            "HTTP_MIME_VERSION": headers["MIME-Version"],
        }
        request = make_request(env)

        response = handler.get_response(request)
        self.assertEqual(file_content, response.content)
        self.assertEqual(recorder, [file_content] * 3) 
Example #21
Source File: test_webapp.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_successful_start_installs_wsgi_resource(self):
        service = self.make_webapp()
        self.addCleanup(service.stopService)

        # Both privileged and and normal start must be called, as twisted
        # multi-service will do the same.
        service.privilegedStartService()
        service.startService()

        # Overlay
        site = service.site
        self.assertThat(site, IsInstance(OverlaySite))
        resource = service.site.resource
        self.assertThat(resource, IsInstance(Resource))
        overlay_resource = resource.getChildWithDefault(b"MAAS", request=None)
        self.assertThat(overlay_resource, IsInstance(Resource))

        # Underlay
        site = service.site.underlay
        self.assertThat(site, IsInstance(Site))
        underlay_resource = site.resource
        self.assertThat(underlay_resource, IsInstance(Resource))
        underlay_maas_resource = underlay_resource.getChildWithDefault(
            b"MAAS", request=None
        )
        self.assertThat(
            underlay_maas_resource, IsInstance(webapp.ResourceOverlay)
        )
        self.assertThat(
            underlay_maas_resource.basis,
            MatchesStructure(
                _reactor=Is(reactor),
                _threadpool=Is(service.threadpool),
                _application=IsInstance(WSGIHandler),
            ),
        ) 
Example #22
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_multipart_boundary(self):
        """
        Invalid boundary string should produce a "Bad Request" response, not a
        server error (#23887).
        """
        environ = RequestFactory().post('/malformed_post/').environ
        environ['CONTENT_TYPE'] = 'multipart/form-data; boundary=WRONG\x07'
        handler = WSGIHandler()
        response = handler(environ, lambda *a, **k: None)
        # Expect "bad request" response
        self.assertEqual(response.status_code, 400) 
Example #23
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_bad_path_info(self):
        """
        A non-UTF-8 path populates PATH_INFO with an URL-encoded path and
        produces a 404.
        """
        environ = RequestFactory().get('/').environ
        environ['PATH_INFO'] = '\xed'
        handler = WSGIHandler()
        response = handler(environ, lambda *a, **k: None)
        # The path of the request will be encoded to '/%ED'.
        self.assertEqual(response.status_code, 404) 
Example #24
Source File: socketio_runserver.py    From tracker_project with MIT License 5 votes vote down vote up
def get_handler(self, *args, **options):
        """
        Returns the django.contrib.staticfiles handler.
        """
        handler = WSGIHandler()
        try:
            from django.contrib.staticfiles.handlers import StaticFilesHandler
        except ImportError:
            return handler
        use_static_handler = options.get('use_static_handler')
        insecure_serving = options.get('insecure_serving', False)
        if (settings.DEBUG and use_static_handler or
                (use_static_handler and insecure_serving)):
            handler = StaticFilesHandler(handler)
        return handler 
Example #25
Source File: test_exception.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_data_upload_max_number_fields_exceeded(self):
        response = WSGIHandler()(self.get_suspicious_environ(), lambda *a, **k: None)
        self.assertEqual(response.status_code, 400) 
Example #26
Source File: test_exception.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_data_upload_max_memory_size_exceeded(self):
        response = WSGIHandler()(self.get_suspicious_environ(), lambda *a, **k: None)
        self.assertEqual(response.status_code, 400) 
Example #27
Source File: test_wsgi.py    From speakerfight with MIT License 5 votes vote down vote up
def test_assert_application(self):
        self.assertIsInstance(application, WSGIHandler) 
Example #28
Source File: test.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def __init__(self):
            self.app = WSGIHandler()
            self.factory = DjangoRequestFactory() 
Example #29
Source File: testcases.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def run(self):
        """
        Sets up the live server and databases, and then loops over handling
        http requests.
        """
        if self.connections_override:
            # Override this thread's database connections with the ones
            # provided by the main thread.
            for alias, conn in self.connections_override.items():
                connections[alias] = conn
        try:
            # Create the handler for serving static and media files
            handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))

            # Go through the list of possible ports, hoping that we can find
            # one that is free to use for the WSGI server.
            for index, port in enumerate(self.possible_ports):
                try:
                    self.httpd = self._create_server(port)
                except socket.error as e:
                    if (index + 1 < len(self.possible_ports) and
                            e.errno == errno.EADDRINUSE):
                        # This port is already in use, so we go on and try with
                        # the next one in the list.
                        continue
                    else:
                        # Either none of the given ports are free or the error
                        # is something else than "Address already in use". So
                        # we let that error bubble up to the main thread.
                        raise
                else:
                    # A free port was found.
                    self.port = port
                    break

            self.httpd.set_app(handler)
            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set() 
Example #30
Source File: desktop_app_main.py    From djanban with MIT License 5 votes vote down vote up
def run(self, netloc='0.0.0.0:9090', reload=True, log=True):
        """Run the CherryPy server."""
        from django.conf import settings
        from django.core.handlers.wsgi import WSGIHandler
        from paste.translogger import TransLogger

        url_parts = urlparse.urlsplit(netloc)
        host = "0.0.0.0"
        port = 9090
        cherrypy.config.update({
            'server.socket_host': host,
            'server.socket_port': port,
            'log.screen': False,
            'engine.autoreload.on': reload,
            'log.access_file': cherry_access_log,
            'log.error_file': cherry_error_log,
        })
        self.cfg_assets(settings.MEDIA_URL, settings.MEDIA_ROOT)
        self.cfg_assets(settings.STATIC_URL, settings.STATIC_ROOT)
        self.cfg_favicon(settings.STATIC_ROOT)
        app = WSGIHandler()
        app = TransLogger(app, logger_name='cherrypy.access',
                          setup_console_handler=False)
        if self.domains:
            app = cherrypy.wsgi.VirtualHost(app, self.domains)
        cherrypy.tree.graft(app)
        cherrypy.engine.start()