def __init__(self, **kwargs): super().__init__() global DEFAULT_HOST, DEFAULT_PORT self.host = kwargs.get('host', DEFAULT_HOST) self.port = kwargs.get('port', DEFAULT_PORT) self.application = WSGIHandler() handler = self.get_staticfiles_handler() if handler: self.application = handler(self.application) if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': self.application = DebuggedApplication(self.application, evalex=True, pin_security=False, pin_logging=False)
def __init__(self, **kwargs): global DEFAULT_HOST, DEFAULT_PORT self.options = { 'accesslog': "-", 'errorlog': "-", 'disable_redirect_access_to_syslog': True, 'workers': (cpu_count() * 2) + 1, 'loglevel': 'info', 'access_log_format': '%(t)s "%(m)s %(U)s%(q)s" %(s)s "%(a)s"', 'bind': "{}:{}".format(kwargs.get('host', DEFAULT_HOST), kwargs.get('port', DEFAULT_PORT)) } self.application = WSGIHandler() super().__init__()
def inner_run(): print "Validating models..." self.validate(display_num_errors=True) print "\nDjango version %s, using settings %r" % ( django.get_version(), settings.SETTINGS_MODULE) print "Development server is running at http://%s:%s/" % (addr, port) print "Using the Werkzeug debugger (http://werkzeug.pocoo.org/)" print "Quit the server with %s." % quit_command path = options.get('admin_media_path', '') if not path: admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin') if os.path.isdir(admin_media_path): path = admin_media_path else: path = os.path.join(django.__path__[0], 'contrib/admin/media') handler = WSGIHandler() if USE_ADMINMEDIAHANDLER: handler = AdminMediaHandler(handler, path) 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 open_browser: import webbrowser url = "http://%s:%s/" % (addr, port) webbrowser.open(url) run_simple(addr, int(port), DebuggedApplication(handler, True), use_reloader=use_reloader, use_debugger=True, threaded=threaded)
def inner_run(): print("Validating models...") try: self.check(display_num_errors=True) except AttributeError: self.validate(display_num_errors=True) 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) path = options.get('admin_media_path', '') if not path: admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin') if os.path.isdir(admin_media_path): path = admin_media_path else: path = os.path.join(django.__path__[0], 'contrib/admin/media') handler = WSGIHandler() if USE_ADMINMEDIAHANDLER: handler = AdminMediaHandler(handler, path) 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 open_browser: import webbrowser webbrowser.open(bind_url) 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: print("Werkzeug version is less than 0.9, trying adhoc certificate.") ssl_context = "adhoc" else: ssl_context = None run_simple( self.addr, int(self.port), DebuggedApplication(handler, True), use_reloader=use_reloader, use_debugger=True, threaded=threaded, ssl_context=ssl_context )
def inner_run(): import os import time try: import hotshot HAS_HOTSPOT = True except ImportError: HAS_HOTSPOT = False # python 3.x USE_CPROFILE = options.get('use_cprofile', False) USE_LSPROF = options.get('use_lsprof', False) if USE_LSPROF: USE_CPROFILE = True if USE_CPROFILE: try: import cProfile USE_CPROFILE = True except ImportError: print("cProfile disabled, module cannot be imported!") USE_CPROFILE = False if USE_LSPROF and not USE_CPROFILE: raise CommandError( "Kcachegrind compatible output format required cProfile from Python 2.5" ) if not HAS_HOTSPOT and not USE_CPROFILE: raise CommandError( "Hotspot profile library not found. (and not using cProfile)" ) prof_path = options.get('prof_path', '/tmp') prof_file = options.get('prof_file', '{path}.{duration:06d}ms.{time}') if not prof_file.format(path='1', duration=2, time=3): prof_file = '{path}.{duration:06d}ms.{time}' print( "Filename format is wrong. Default format used: '{path}.{duration:06d}ms.{time}'." ) def get_exclude_paths(): exclude_paths = [] media_url = getattr(settings, 'MEDIA_URL', None) if media_url: exclude_paths.append(media_url) static_url = getattr(settings, 'STATIC_URL', None) if static_url: exclude_paths.append(static_url) admin_media_prefix = getattr(settings, 'ADMIN_MEDIA_PREFIX', None) if admin_media_prefix: exclude_paths.append(admin_media_prefix) return exclude_paths def make_profiler_handler(inner_handler): def handler(environ, start_response): path_info = environ['PATH_INFO'] # when using something like a dynamic site middleware is could be necessary # to refetch the exclude_paths every time since they could change per site. if no_media and any( path_info.startswith(p) for p in get_exclude_paths()): return inner_handler(environ, start_response) path_name = path_info.strip("/").replace('/', '.') or "root" profname = "%s.%d.prof" % (path_name, time.time()) profname = os.path.join(prof_path, profname) if USE_CPROFILE: prof = cProfile.Profile() else: prof = hotshot.Profile(profname) start = datetime.now() try: return prof.runcall(inner_handler, environ, start_response) finally: # seeing how long the request took is important! elap = datetime.now() - start elapms = elap.seconds * 1000.0 + elap.microseconds / 1000.0 if USE_LSPROF: kg = KCacheGrind(prof) with open(profname, 'w') as f: kg.output(f) elif USE_CPROFILE: prof.dump_stats(profname) profname2 = prof_file.format(path=path_name, duration=int(elapms), time=int(time.time())) profname2 = os.path.join(prof_path, "%s.prof" % profname2) if not USE_CPROFILE: prof.close() os.rename(profname, profname2) return handler print("Validating models...") if hasattr(self, 'check'): self.check(display_num_errors=True) else: self.validate(display_num_errors=True) print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)) print("Development server is running at http://%s:%s/" % (addr, port)) print("Quit the server with %s." % quit_command) path = options.get('admin_media_path', '') if not path: admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin') if os.path.isdir(admin_media_path): path = admin_media_path else: path = os.path.join(django.__path__[0], 'contrib/admin/media') try: handler = WSGIHandler() if HAS_ADMINMEDIAHANDLER: handler = AdminMediaHandler(handler, path) 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) handler = make_profiler_handler(handler) run(addr, int(port), handler) except wsgi_server_exc_cls 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.", } if not isinstance(e, socket.error): # Django < 1.6 ERRORS[13] = ERRORS.pop(errno.EACCES) ERRORS[98] = ERRORS.pop(errno.EADDRINUSE) ERRORS[99] = ERRORS.pop(errno.EADDRNOTAVAIL) try: if not isinstance(e, socket.error): # Django < 1.6 error_text = ERRORS[e.args[0].args[0]] else: error_text = ERRORS[e.errno] except (AttributeError, KeyError): error_text = str(e) sys.stderr.write( self.style.ERROR("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: if shutdown_message: print(shutdown_message) sys.exit(0)
def inner_run(self, options): import django try: from werkzeug import run_simple, DebuggedApplication # Set colored output if settings.DEBUG: try: set_werkzeug_log_color() except: # 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)" ) 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' bind_url = "http://%s:%s/" % (self.addr if not self._raw_ipv6 else '[%s]' % self.addr, self.port) extra_files = options.get('extra_files', None) or [] reloader_interval = options.get('reloader_interval', 1) 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) if HAS_MIGRATIONS: try: self.check_migrations() except ImproperlyConfigured: pass 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) path = options.get('admin_media_path', '') if not path: admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin') if os.path.isdir(admin_media_path): path = admin_media_path else: path = os.path.join(django.__path__[0], 'contrib/admin/media') handler = WSGIHandler() if USE_ADMINMEDIAHANDLER: handler = AdminMediaHandler(handler, path) 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 open_browser: import webbrowser webbrowser.open(bind_url) 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 if use_reloader and settings.USE_I18N: try: from django.utils.autoreload import gen_filenames except ImportError: pass else: 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': 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, threaded=threaded, ssl_context=ssl_context, )