def test_bad_module(self): with self.assertRaises(ImproperlyConfigured) as cm: get_internal_wsgi_application() self.assertEqual( str(cm.exception), "WSGI application 'regressiontests.wsgi.noexist.app' could not be loaded; could not import module 'regressiontests.wsgi.noexist': No module named noexist")
def test_bad_name(self): with six.assertRaisesRegex( self, ImproperlyConfigured, r"WSGI application 'fiware_cloto.cloto.wsgi.noexist' could not be loaded; Error importing module:" r" 'Module \"fiware_cloto.cloto.wsgi\" does not define a \"noexist\" attribute/class'" ): get_internal_wsgi_application()
def test_bad_name(self): with self.assertRaises(ImproperlyConfigured) as cm: get_internal_wsgi_application() self.assertEqual( str(cm.exception), "WSGI application 'regressiontests.wsgi.wsgi.noexist' could not be loaded; can't find 'noexist' in module 'regressiontests.wsgi.wsgi': 'module' object has no attribute 'noexist'")
def test_bad_name(self): with six.assertRaisesRegex( self, ImproperlyConfigured, r"^WSGI application 'wsgi.wsgi.noexist' could not be loaded; Error importing.*" ): get_internal_wsgi_application()
def test_bad_module(self): with self.assertRaisesRegexp( ImproperlyConfigured, r"^WSGI application 'regressiontests.wsgi.noexist.app' could not be loaded; could not import module 'regressiontests.wsgi.noexist':" ): get_internal_wsgi_application()
def test_bad_name(self): with self.assertRaisesRegexp( ImproperlyConfigured, r"^WSGI application 'regressiontests.wsgi.wsgi.noexist' could not be loaded; can't find 'noexist' in module 'regressiontests.wsgi.wsgi':" ): get_internal_wsgi_application()
def test_bad_name(self): with self.assertRaisesRegexp( ImproperlyConfigured, r"^WSGI application 'regressiontests.wsgi.wsgi.noexist' could not be loaded; can't find 'noexist' in module 'regressiontests.wsgi.wsgi':", ): get_internal_wsgi_application()
def test_bad_module(self): with self.assertRaisesRegexp( ImproperlyConfigured, r"^WSGI application 'regressiontests.wsgi.noexist.app' could not be loaded; could not import module 'regressiontests.wsgi.noexist':", ): get_internal_wsgi_application()
def test_bad_name(self): with six.assertRaisesRegex( self, ImproperlyConfigured, r"^WSGI application 'regressiontests.wsgi.wsgi.noexist' could not be loaded; Module.*" ): get_internal_wsgi_application()
def __init__(self, media_path: Optional[str] = None, storage: Optional[Storage] = None, index_url_name: Optional[str] = None, sitemaps_view_name: Optional[str] = None, sitemaps: Optional[Dict[str, Type[Sitemap]]] = None): """ :param media_path: relative path on file storage :param storage: file storage implementation used for sitemaps :param index_url_name: name of view serving sitemap index xml file :param sitemaps_view_name: name of view serving indexed sitemaps :param sitemaps: mapping: sitemap name -> sitemap implementation """ cls = self.__class__ self.logger = getLogger(f'{cls.__module__}.{cls.__name__}') self.sitemap_root = media_path or defaults.SITEMAP_MEDIA_PATH storage = storage or defaults.SITEMAP_STORAGE self.storage = import_string(storage) self.index_url_name = index_url_name or defaults.SITEMAP_INDEX_NAME sitemaps_view_name = sitemaps_view_name or defaults.SITEMAPS_VIEW_NAME self.sitemaps_view_name = sitemaps_view_name sitemaps = sitemaps or getattr(settings, 'SITEMAP_MAPPING') self.sitemaps = import_string(sitemaps) self.recorder = ResponseRecorder( basehttp.get_internal_wsgi_application())
def wsgi_resource(): pool = threadpool.ThreadPool() pool.start() # Allow Ctrl-C to get you out cleanly: reactor.addSystemEventTrigger('after', 'shutdown', pool.stop) wsgi_resource = wsgi.WSGIResource(reactor, pool, get_internal_wsgi_application()) return wsgi_resource
def get_handler(self, *args, **options): """ Returns the default WSGI handler for the runner. """ handler = get_internal_wsgi_application() from django.contrib.staticfiles.handlers import StaticFilesHandler return StaticFilesHandler(handler)
def handle(self, addr_port=None, pool_size=None, *args, **options): if args: raise CommandError('Usage: [ipaddr:]addr_port pool_size') addr_port = addr_port or getattr(settings, 'GEVENT_ADDR_PORT', defaults['GEVENT_ADDR_PORT']) pool_size = pool_size or getattr(settings, 'GEVENT_POOL_SIZE', defaults['GEVENT_POOL_SIZE']) try: addr, port = addr_port.split(':') except ValueError: addr, port = '', addr_port try: port = int(port) except ValueError: raise CommandError('Port must be an integer') if pool_size: try: pool_size = int(pool_size) pool = Pool(pool_size) except ValueError: raise CommandError('Spawn pool size must be an integer') else: pool = None wsgi_application = get_internal_wsgi_application() wsgi.WSGIServer((addr, port), wsgi_application, spawn=pool).serve_forever()
def test_file_response_call_request_finished(self): env = RequestFactory().get("/fileresponse/").environ handler = FileWrapperHandler(None, BytesIO(), BytesIO(), env) with mock.MagicMock() as signal_handler: request_finished.connect(signal_handler) handler.run(get_internal_wsgi_application()) self.assertEqual(signal_handler.call_count, 1)
def get_handler(self, *args, **options): """ Returns the default WSGI handler for the runner. """ handler = get_internal_wsgi_application() from django.contrib.staticfiles.handlers import StaticFilesHandler return StaticFilesHandler(handler)
def test_success(self): """ If ``WSGI_APPLICATION`` is a dotted path, the referenced object is returned. """ app = get_internal_wsgi_application() from fiware_cloto.cloto.wsgi import application self.assertTrue(app is application)
def wsgi_resource(): pool = threadpool.ThreadPool() pool.start() # Allow Ctrl-C to get you out cleanly: reactor.addSystemEventTrigger('after', 'shutdown', pool.stop) handler = StaticFilesHandler(get_internal_wsgi_application()) wsgi_resource = wsgi.WSGIResource(reactor, pool, handler) return wsgi_resource
def start_server(self): try: handler = get_internal_wsgi_application() self.HTTPD = StoppableWSGIServer(('', PORT), WSGIRequestHandler) self.HTTPD.set_app(handler) self.HTTPD.serve_forever() except KeyboardInterrupt: sys.exit(0)
def test_success(self): """ If ``WSGI_APPLICATION`` is a dotted path, the referenced object is returned. """ app = get_internal_wsgi_application() from fiware_cloto.cloto.wsgi import application self.assertTrue(app is application)
def get_django_handlers(self): # django_application = django.core.handlers.wsgi.WSGIHandler() django_application = get_internal_wsgi_application() django_wsgi = tornado.wsgi.WSGIContainer(django_application) handlers = [ (r'.*', tornado.web.FallbackHandler, dict(fallback=django_wsgi)), ] return handlers
def start_server(self): try: handler = get_internal_wsgi_application() self.HTTPD = StoppableWSGIServer(('', PORT), WSGIRequestHandler) self.HTTPD.set_app(handler) self.HTTPD.serve_forever() except KeyboardInterrupt: sys.exit(0)
def serve(self): self.keys = self._load_keys() self.enable_auth = self.get_config_json("enable_auth") if self.enable_auth is None: self.enable_auth = True app = get_internal_wsgi_application() from rest_framework import authentication class KeyUser(object): def __init__(self, username): self.username = username def is_authenticated(self): return True # Take a local reference to use inside the APIKeyAuthentication # class definition log = self.log # Configure django.request logger logging.getLogger("django.request").handlers = self.log.handlers logging.getLogger("django.request").setLevel(logging.DEBUG) class APIKeyAuthentication(authentication.BaseAuthentication): def authenticate(self, request): if not global_instance().enable_auth: return KeyUser("anonymous"), None username = request.META.get('HTTP_X_USERNAME') if not username: log.warning("Rejecting: no X_USERNAME") return None if username not in global_instance().keys: log.warning("Rejecting: username does not exist") return None api_key = request.META.get('HTTP_X_APIKEY') expect_key = global_instance().keys[username] if api_key != expect_key: log.warning("Rejecting: wrong API key") return None log.debug("Accepted for user {0}".format(username)) return KeyUser(username), None self._auth_cls = APIKeyAuthentication cherrypy.config.update({ 'server.socket_port': 8002, 'engine.autoreload.on': False }) cherrypy.tree.graft(app, '/') cherrypy.engine.start() cherrypy.engine.block()
def serve(self): self.keys = self._load_keys() self.enable_auth = self.get_config_json("enable_auth") if self.enable_auth is None: self.enable_auth = True app = get_internal_wsgi_application() from rest_framework import authentication class KeyUser(object): def __init__(self, username): self.username = username def is_authenticated(self): return True # Take a local reference to use inside the APIKeyAuthentication # class definition log = self.log # Configure django.request logger logging.getLogger("django.request").handlers = self.log.handlers logging.getLogger("django.request").setLevel(logging.DEBUG) class APIKeyAuthentication(authentication.BaseAuthentication): def authenticate(self, request): if not global_instance().enable_auth: return KeyUser("anonymous"), None username = request.META.get('HTTP_X_USERNAME') if not username: log.warning("Rejecting: no X_USERNAME") return None if username not in global_instance().keys: log.warning("Rejecting: username does not exist") return None api_key = request.META.get('HTTP_X_APIKEY') expect_key = global_instance().keys[username] if api_key != expect_key: log.warning("Rejecting: wrong API key") return None log.debug("Accepted for user {0}".format(username)) return KeyUser(username), None self._auth_cls = APIKeyAuthentication cherrypy.config.update({ 'server.socket_port': 8002, 'engine.autoreload.on': False }) cherrypy.tree.graft(app, '/') cherrypy.engine.start() cherrypy.engine.block()
def run_server(cls, host, port): handler = StaticFilesHandler(get_internal_wsgi_application()) # Save the event loop for the thread in a class variable # so we can unblock it when the tests are finished. cls.server_thread_loop = asyncio.new_event_loop() asyncio.set_event_loop(cls.server_thread_loop) cls.server_stop = asyncio.Future() run(host, port, handler, cls.server_thread_loop, cls.server_stop) cls.server_thread_loop.close()
def run_server(cls, host, port): handler = StaticFilesHandler(get_internal_wsgi_application()) # Save the event loop for the thread in a class variable # so we can unblock it when the tests are finished. cls.server_thread_loop = asyncio.new_event_loop() asyncio.set_event_loop(cls.server_thread_loop) cls.server_stop = asyncio.Future() run(host, port, handler, cls.server_thread_loop, cls.server_stop) cls.server_thread_loop.close()
def test_success(self): """ If ``WSGI_APPLICATION`` is a dotted path, the referenced object is returned. """ app = get_internal_wsgi_application() from hx_lti_tools.wsgi import application self.assertIs(app, application)
def run(self, **options): autoreload.raise_last_exception() self.check(display_num_errors=True) self.stdout.write(self.style.SUCCESS('Server is running!')) run(addr="127.0.0.1", port=8000, wsgi_handler=get_internal_wsgi_application(), threading=True, server_cls=WSGIServer)
def test_success(self): """ If ``WSGI_APPLICATION`` is a dotted path, the referenced object is returned. """ app = get_internal_wsgi_application() from config.wsgi import application self.assertIs(app, application)
def main(settings_file, logfile=None): os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_file) # Setup settings if logfile: redirect_streams(logfile) from django.core.servers.basehttp import get_internal_wsgi_application return get_internal_wsgi_application()
def main(settings_file, logfile=None): os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_file) # Setup settings if logfile: redirect_streams(logfile) from django.core.servers.basehttp import get_internal_wsgi_application return get_internal_wsgi_application()
def get_django_handlers(self): # django_application = django.core.handlers.wsgi.WSGIHandler() django_application = get_internal_wsgi_application() django_wsgi = tornado.wsgi.WSGIContainer(django_application) handlers = [ ( r'.*', tornado.web.FallbackHandler, dict(fallback=django_wsgi) ), ] return handlers
def main(): os.environ['DJANGO_SETTINGS_MODULE'] = 'mathics.settings' #os.putenv('DJANGO_SETTINGS_MODULE', 'mathics.settings') from django.conf import settings from django.core.servers.basehttp import run, WSGIServerException from django.core.handlers.wsgi import WSGIHandler parser = OptionParser(version='%prog ' + settings.VERSION, description="Mathics server for the graphical user interface in Firefox. It is not intended for production use on a public Web server!") parser.add_option("-p", "--port", dest="port", metavar="PORT", default=8000, type='int', help="use PORT as server port") parser.add_option("-e", "--external", dest="external", action="store_true", help="allow external access to server") options, args = parser.parse_args() print_version(is_server=True) print_license() quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' print u"Quit by pressing %s\n" % quit_command port = options.port print u"Open the graphical user interface at\nhttp://localhost:%d\nin Firefox, Chrome, or Safari to use Mathics\n" % port if options.external: addr = '0.0.0.0' else: addr = '' try: if settings.DJANGO_VERSION < (1, 4): from django.core.servers.basehttp import AdminMediaHandler handler = AdminMediaHandler(WSGIHandler(), '') else: from django.core.servers.basehttp import get_internal_wsgi_application handler = get_internal_wsgi_application() run(addr, port, handler) except WSGIServerException, e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { 13: "You don't have permission to access that port.", 98: "That port is already in use.", 99: "That IP address can't be assigned to.", } try: error_text = ERRORS[e.args[0].args[0]] except (AttributeError, KeyError): error_text = str(e) sys.stderr.write("Error: %s" % error_text + '\n') # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1)
def setup_test_environment(self, **kwargs): super(TestSuiteRunner, self).setup_test_environment(**kwargs) handler = get_internal_wsgi_application() handler = StaticFilesHandler(handler) def start_server(): with patch('django.core.servers.basehttp.WSGIRequestHandler.log_message'): run('0.0.0.0', 65432, handler, ipv6=False, threading=False) thread = threading.Thread(target=start_server) thread.daemon = True thread.start() global BROWSER BROWSER = SingleVisitFirefoxDriver()
def make_wsgi_application(): # validate models s = StringIO() import django from django.core.management.base import BaseCommand django.setup() cmd = BaseCommand() import sys cmd.stdout, cmd.stderr = sys.stdout, sys.stderr cmd.check() translation.activate(settings.LANGUAGE_CODE) if django14: return get_internal_wsgi_application() return WSGIHandler()
def make_wsgi_application(): # validate models s = StringIO() if get_validation_errors(s): s.seek(0) error = s.read() sys.stderr.write("One or more models did not validate:\n%s" % error) sys.stderr.flush() sys.exit(1) translation.activate(settings.LANGUAGE_CODE) if django14: return get_internal_wsgi_application() return WSGIHandler()
def run(self): """ Sets up the live server and databases, and then loops over handling http requests. """ server_address = (self.host, self.port) threading = True if threading: httpd_cls = type('WSGIServer', (ThreadingMixIn, WSGIServer), {}) else: httpd_cls = WSGIServer self.httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=False) wsgi_handler = get_internal_wsgi_application() self.httpd.set_app(wsgi_handler) self.is_ready.set() self.httpd.serve_forever()
def run(self, addr_port=None, pool_size=None, *args, **options): if args: raise CommandError('Usage: [ipaddr:]addr_port pool_size') addr_port = addr_port or getattr(settings, 'GEVENT_ADDR_PORT', defaults['GEVENT_ADDR_PORT']) pool_size = pool_size or getattr(settings, 'GEVENT_POOL_SIZE', defaults['GEVENT_POOL_SIZE']) try: addr, port = addr_port.split(':') except ValueError: addr, port = '', addr_port try: port = int(port) except ValueError: raise CommandError('Port must be an integer') if pool_size: try: pool_size = int(pool_size) pool = Pool(pool_size) except ValueError: raise CommandError('Spawn pool size must be an integer') else: pool = None quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' self.stdout.write("Validating models...\n\n") self.validate(display_num_errors=True) self.stdout.write(( "%(started_at)s\n" "Django version %(version)s, using settings %(settings)r\n" "Development server is running at http://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n" ) % { "started_at": datetime.now().strftime('%B %d, %Y - %X'), "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "addr": addr, "port": port, "quit_command": quit_command, }) wsgi_application = get_internal_wsgi_application() wsgi.WSGIServer((addr, port), wsgi_application, spawn=pool).serve_forever()
def handle(self, *args, **options): self.options = options # Get this Django Project's WSGI Application and mount it application = get_internal_wsgi_application() cherrypy.tree.graft(application, "/") # Unsubscribe the default server cherrypy.server.unsubscribe() # Instantiate a new server server = cherrypy._cpserver.Server() # Configure the server server.socket_host = self.options['host'] server.socket_port = self.options['app_port'] server.thread_pool = 30 server.max_request_body_size = 10737412742 # For SSL Support # server.ssl_module = 'pyopenssl' # server.ssl_certificate = 'ssl/certificate.crt' # server.ssl_private_key = 'ssl/private.key' # server.ssl_certificate_chain = 'ssl/bundle.crt # Subscribe the new server server.subscribe() cherrypy.engine.start() #cherrypy.engine.block() # I would like to use this as it listens to other CherryPy bad states. However, it causes the application to not catch the system close call correctly try: while (True): sleep(.1) except (KeyboardInterrupt, IOError, SystemExit) as e: try: print("Attempting to shutdown the server...") cherrypy.engine.exit( ) # Need to call this first since we aren't blocking above print("Server shutdown.") except: print("Failed to shutdown server! Please press 'Ctrl+c.'")
def test_default(self): """ If ``WSGI_APPLICATION`` is ``None``, the return value of ``get_wsgi_application`` is returned. """ # Mock out get_wsgi_application so we know its return value is used fake_app = object() def mock_get_wsgi_app(): return fake_app from django.core.servers import basehttp _orig_get_wsgi_app = basehttp.get_wsgi_application basehttp.get_wsgi_application = mock_get_wsgi_app try: app = get_internal_wsgi_application() self.assertTrue(app is fake_app) finally: basehttp.get_wsgi_application = _orig_get_wsgi_app
def test_file_response_closing(self): """ View returning a FileResponse properly closes the file and http response when file_wrapper is used. """ env = RequestFactory().get("/fileresponse/").environ handler = FileWrapperHandler(None, BytesIO(), BytesIO(), env) handler.run(get_internal_wsgi_application()) # Sendfile is used only when file_wrapper has been used. self.assertTrue(handler._used_sendfile) # Fetch the original response object. self.assertIn("response", FILE_RESPONSE_HOLDER) response = FILE_RESPONSE_HOLDER["response"] # The response and file buffers are closed. self.assertIs(response.closed, True) buf1, buf2 = FILE_RESPONSE_HOLDER["buffers"] self.assertIs(buf1.closed, True) self.assertIs(buf2.closed, True) FILE_RESPONSE_HOLDER.clear()
def test_default(self): """ If ``WSGI_APPLICATION`` is ``None``, the return value of ``get_wsgi_application`` is returned. """ # Mock out get_wsgi_application so we know its return value is used fake_app = object() def mock_get_wsgi_app(): return fake_app from django.core.servers import basehttp _orig_get_wsgi_app = basehttp.get_wsgi_application basehttp.get_wsgi_application = mock_get_wsgi_app try: app = get_internal_wsgi_application() self.assertTrue(app is fake_app) finally: basehttp.get_wsgi_application = _orig_get_wsgi_app
def handle(self, *args, **options): self.options = options # Get this Django Project's WSGI Application and mount it application = get_internal_wsgi_application() cherrypy.tree.graft(application, "/") # Unsubscribe the default server cherrypy.server.unsubscribe() # Instantiate a new server server = cherrypy._cpserver.Server() # Configure the server server.socket_host = self.options['host'] server.socket_port = self.options['app_port'] server.thread_pool = 30 server.max_request_body_size = 10737412742 # For SSL Support # server.ssl_module = 'pyopenssl' # server.ssl_certificate = 'ssl/certificate.crt' # server.ssl_private_key = 'ssl/private.key' # server.ssl_certificate_chain = 'ssl/bundle.crt # Subscribe the new server server.subscribe() cherrypy.engine.start() #cherrypy.engine.block() # I would like to use this as it listens to other CherryPy bad states. However, it causes the application to not catch the system close call correctly try: while(True): sleep(.1) except (KeyboardInterrupt, IOError, SystemExit) as e: try: print("Attempting to shutdown the server...") cherrypy.engine.exit() # Need to call this first since we aren't blocking above print("Server shutdown.") except: print("Failed to shutdown server! Please press 'Ctrl+c.'")
def launch_app(args): quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' port = args.port if not args.quiet: print() print(server_version_string) print() print(license_string) print() print("Quit by pressing %s\n" % quit_command) print("""Open the graphical user interface at http://localhost:%d\nin Firefox, Chrome, or Safari to use Mathics\n""" % port) if args.external: addr = '0.0.0.0' else: addr = '127.0.0.1' try: from django.core.servers.basehttp import (run, get_internal_wsgi_application ) handler = get_internal_wsgi_application() run(addr, port, handler) except socket.error as e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { errno.EACCES: "You don't have permission to access that port.", errno.EADDRINUSE: "That port is already in use.", errno.EADDRNOTAVAIL: "That IP address can't be assigned to.", } try: error_text = ERRORS[e.errno] except KeyError: error_text = str(e) sys.stderr.write("Error: %s" % error_text + '\n') # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: print("\nGoodbye!\n") sys.exit(0)
def __init__(self, media_path: str = 'sitemaps', storage: Storage = default_storage, index_url_name: str = 'sitemap-index', sitemaps: Optional[Dict[str, Type[Sitemap]]] = None): """ :param media_path: relative path on file storage :param storage: file storage implementation used for sitemaps :param index_url_name: name of view serving sitemap index xml file :param sitemaps: mapping: sitemap name -> sitemap implementation """ cls = self.__class__ self.logger = getLogger(f'{cls.__module__}.{cls.__name__}') self.sitemap_root = media_path self.storage = storage self.index_url_name = index_url_name self.sitemaps = sitemaps or {} self.recorder = ResponseRecorder( basehttp.get_internal_wsgi_application())
def launch_app(args): quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' port = args.port if not args.quiet: print() print(server_version_string) print() print(license_string) print() print("Quit by pressing %s\n" % quit_command) print("""Open the graphical user interface at http://localhost:%d\nin Firefox, Chrome, or Safari to use Mathics\n""" % port) if args.external: addr = '0.0.0.0' else: addr = '127.0.0.1' try: from django.core.servers.basehttp import ( run, get_internal_wsgi_application) handler = get_internal_wsgi_application() run(addr, port, handler) except socket.error as e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { errno.EACCES: "You don't have permission to access that port.", errno.EADDRINUSE: "That port is already in use.", errno.EADDRNOTAVAIL: "That IP address can't be assigned to.", } try: error_text = ERRORS[e.errno] except KeyError: error_text = str(e) sys.stderr.write("Error: %s" % error_text + '\n') # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: print("\nGoodbye!\n") sys.exit(0)
def handle(self, *args, **options): m = re.match(naiveip_re, options['addrport']) if m is None: raise CommandError('"%s" is not a valid port number ' 'or address:port pair.' % options['addrport']) addr, _ipv4, _ipv6, _fqdn, port = m.groups() if not port.isdigit(): raise CommandError("%r is not a valid port number." % port) if addr: if _ipv6: raise CommandError( 'IPv6 addresses are currently not supported.') application = get_internal_wsgi_application() server = Server(application) for file in os.listdir('.'): if file[0] != '.' and file[:2] != '__' and os.path.isdir(file): server.watch(file) server.serve(host=addr, port=port, liveport=options['liveport'])
def handle(self, *args, **options): m = re.match(naiveip_re, options['addrport']) if m is None: raise CommandError('"%s" is not a valid port number ' 'or address:port pair.' % options['addrport']) addr, _ipv4, _ipv6, _fqdn, port = m.groups() if not port.isdigit(): raise CommandError("%r is not a valid port number." % port) if addr: if _ipv6: raise CommandError('IPv6 addresses are currently not supported.') application = get_internal_wsgi_application() server = Server(application) for file in os.listdir('.'): if file[0] != '.' and file[:2] != '__' and os.path.isdir(file): server.watch(file) server.serve(host=addr, port=port, liveport=options['liveport'])
def get_handler(self, *args, **options): """ Returns the default WSGI handler for the runner. """ return get_internal_wsgi_application()
def get_handler(self, *args, **options): """Return the default WSGI handler for the runner.""" return get_internal_wsgi_application()
def inner_run(self, options): import django try: from werkzeug import run_simple, DebuggedApplication from werkzeug.serving import WSGIRequestHandler as _WSGIRequestHandler # Set colored output if settings.DEBUG: try: set_werkzeug_log_color() except Exception: # We are dealing with some internals, anything could go wrong if self.show_startup_messages: print("Wrapping internal werkzeug logger for color highlighting has failed!") pass except ImportError: raise CommandError("Werkzeug is required to use runserver_plus. Please visit http://werkzeug.pocoo.org/ or install via pip. (pip install Werkzeug)") class WSGIRequestHandler(_WSGIRequestHandler): def make_environ(self): environ = super(WSGIRequestHandler, self).make_environ() if not options.get('keep_meta_shutdown_func'): del environ['werkzeug.server.shutdown'] return environ threaded = options.get('threaded', True) use_reloader = options.get('use_reloader', True) open_browser = options.get('open_browser', False) cert_path = options.get("cert_path") quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' extra_files = options.get('extra_files', None) or [] reloader_interval = options.get('reloader_interval', 1) reloader_type = options.get('reloader_type', 'auto') self.nopin = options.get('nopin', False) if self.show_startup_messages: print("Performing system checks...\n") if hasattr(self, 'check'): self.check(display_num_errors=self.show_startup_messages) else: self.validate(display_num_errors=self.show_startup_messages) try: self.check_migrations() except ImproperlyConfigured: pass handler = get_internal_wsgi_application() if USE_STATICFILES: use_static_handler = options.get('use_static_handler', True) insecure_serving = options.get('insecure_serving', False) if use_static_handler and (settings.DEBUG or insecure_serving): handler = StaticFilesHandler(handler) if cert_path: """ OpenSSL is needed for SSL support. This will make flakes8 throw warning since OpenSSL is not used directly, alas, this is the only way to show meaningful error messages. See: http://lucumr.pocoo.org/2011/9/21/python-import-blackbox/ for more information on python imports. """ try: import OpenSSL # NOQA except ImportError: raise CommandError("Python OpenSSL Library is " "required to use runserver_plus with ssl support. " "Install via pip (pip install pyOpenSSL).") dir_path, cert_file = os.path.split(cert_path) if not dir_path: dir_path = os.getcwd() root, ext = os.path.splitext(cert_file) certfile = os.path.join(dir_path, root + ".crt") keyfile = os.path.join(dir_path, root + ".key") try: from werkzeug.serving import make_ssl_devcert if os.path.exists(certfile) and \ os.path.exists(keyfile): ssl_context = (certfile, keyfile) else: # Create cert, key files ourselves. ssl_context = make_ssl_devcert( os.path.join(dir_path, root), host='localhost') except ImportError: if self.show_startup_messages: print("Werkzeug version is less than 0.9, trying adhoc certificate.") ssl_context = "adhoc" else: ssl_context = None bind_url = "%s://%s:%s/" % ( "https" if ssl_context else "http", self.addr if not self._raw_ipv6 else '[%s]' % self.addr, self.port) if self.show_startup_messages: print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)) print("Development server is running at %s" % (bind_url,)) print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)") print("Quit the server with %s." % quit_command) if open_browser: import webbrowser webbrowser.open(bind_url) if use_reloader and settings.USE_I18N: extra_files.extend(filter(lambda filename: filename.endswith('.mo'), gen_filenames())) # Werkzeug needs to be clued in its the main instance if running # without reloader or else it won't show key. # https://git.io/vVIgo if not use_reloader: os.environ['WERKZEUG_RUN_MAIN'] = 'true' # Don't run a second instance of the debugger / reloader # See also: https://github.com/django-extensions/django-extensions/issues/832 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': if self.nopin: os.environ['WERKZEUG_DEBUG_PIN'] = 'off' handler = DebuggedApplication(handler, True) run_simple( self.addr, int(self.port), handler, use_reloader=use_reloader, use_debugger=True, extra_files=extra_files, reloader_interval=reloader_interval, reloader_type=reloader_type, threaded=threaded, request_handler=WSGIRequestHandler, ssl_context=ssl_context, )
def test_bad_name(self): msg = "WSGI application 'wsgi.wsgi.noexist' could not be loaded; Error importing" with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application()
else: logger.warn( "Instana: Couldn't add InstanaMiddleware to Django") else: logger.warn("Instana: Couldn't find middleware settings") return wrapped(*args, **kwargs) except Exception: logger.warn("Instana: Couldn't add InstanaMiddleware to Django: ", exc_info=True) try: if 'django' in sys.modules: logger.debug("Instrumenting django") wrapt.wrap_function_wrapper('django.core.handlers.base', 'BaseHandler.load_middleware', load_middleware_wrapper) if 'INSTANA_MAGIC' in os.environ: # If we are instrumenting via AutoTrace (in an already running process), then the # WSGI middleware has to be live reloaded. from django.core.servers.basehttp import get_internal_wsgi_application wsgiapp = get_internal_wsgi_application() wsgiapp.load_middleware() except Exception: logger.debug("django.middleware:", exc_info=True) pass
def test_bad_name(self): with six.assertRaisesRegex(self, ImproperlyConfigured, r"^WSGI application 'wsgi.wsgi.noexist' could not be loaded; Module.*"): get_internal_wsgi_application()
def test_bad_module(self): with six.assertRaisesRegex(self, ImproperlyConfigured, r"^WSGI application 'wsgi.noexist.app' could not be loaded; Error importing.*"): get_internal_wsgi_application()
def _get_django_wsgi_app(): # The following module can only be imported after the settings have been # set. from django.core.servers.basehttp import get_internal_wsgi_application wsgi_application = get_internal_wsgi_application() return wsgi_application
daemonize = (wsgi_opts['bindAddress'] is not None) else: if options["daemonize"].lower() in ('true', 'yes', 't'): daemonize = True elif options["daemonize"].lower() in ('false', 'no', 'f'): daemonize = False else: return fastcgi_help("ERROR: Invalid option for daemonize parameter.") daemon_kwargs = {} if options['outlog']: daemon_kwargs['out_log'] = options['outlog'] if options['errlog']: daemon_kwargs['err_log'] = options['errlog'] if options['umask']: daemon_kwargs['umask'] = int(options['umask'], 8) if daemonize: from django.utils.daemonize import become_daemon become_daemon(our_home_dir=options["workdir"], **daemon_kwargs) if options["pidfile"]: fp = open(options["pidfile"], "w") fp.write("%d\n" % os.getpid()) fp.close() WSGIServer(get_internal_wsgi_application(), **wsgi_opts).run() if __name__ == '__main__': runfastcgi(sys.argv[1:])