def inner_run(): from django.conf import settings from django.utils import translation 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 "Quit the server with %s." % quit_command # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: path = admin_media_path or django.__path__[0] + '/contrib/admin/media' handler = disable_admin_media and WSGIHandler() or AdminMediaHandler(WSGIHandler(), path) run(addr, int(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(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)
def inner_run(): from django.conf import settings from django.utils import translation 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 "Quit the server with %s." % quit_command # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: handler = AdminMediaHandler(WSGIHandler(), admin_media_path) run(addr, int(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(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)
def main(): import os import sys sys.path.insert(0, "..") os.environ['DJANGO_SETTINGS_MODULE'] = "plotserver.settings" from django.core.servers.basehttp import run, AdminMediaHandler, WSGIServerException from django.core.handlers.wsgi import WSGIHandler addr = '127.0.0.1' port = '8000' admin_media_path = '' try: handler = AdminMediaHandler(WSGIHandler(), admin_media_path) print "Server is running at http://%s:%s/" % (addr, port) print "Quit the server with CONTROL-C." run(addr, int(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) print "Error: %s" % error_text # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1)
def inner_run(): from django.conf import settings print "Validating models..." self.validate(display_num_errors=True) if hasattr(settings, 'GADGETS_ROOT'): print "\nLoading gadgets..." from commons.utils import load_gadgets load_gadgets() 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 try: path = admin_media_path or django.__path__[ 0] + '/contrib/admin/media' handler = AdminMediaHandler(WSGIHandler(), path) run(addr, int(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( 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)
def runner(): try: os.environ['DJANGO_SETTINGS_MODULE'] = 'stack.restapi.settings' basehttp.run('127.0.0.1', 8000, get_wsgi_application()) except KeyboardInterrupt: # The signal to exit pass
def inner_run(): from django.conf import settings from django.utils import translation 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://0.0.0.0:8000" print "Quit the server with CONTROL-C." translation.activate(settings.LANGUAGE_CODE) try: path = django.__path__[0] + '/contrib/admin/media' handler = AdminMediaHandler(WSGIHandler(), path) run("0.0.0.0", 8000, handler) except WSGIServerException, e: 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(self.style.ERROR("Error: %s" % error_text) + '\n') _stop_bonjour() os._exit(1)
def inner_run(): from django.conf import settings print "Validating models..." self.validate(display_num_errors=True) if hasattr(settings, 'GADGETS_ROOT'): print "\nLoading gadgets..." from commons.utils import load_gadgets load_gadgets() 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 try: path = admin_media_path or django.__path__[0] + '/contrib/admin/media' handler = AdminMediaHandler(WSGIHandler(), path) run(addr, int(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(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)
def inner_run(self, *args, **options): from django.conf import settings from django.utils import translation threading = options.get('use_threading') shutdown_message = options.get('shutdown_message', '') quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' self.stdout.write("Performing system checks...\n\n") self.validate(display_num_errors=True) try: self.check_migrations() except ImproperlyConfigured: pass now = datetime.now().strftime('%B %d, %Y - %X') if six.PY2: now = now.decode(get_system_encoding()) self.stdout.write( ("%(started_at)s\n" "Django version %(version)s, using settings %(settings)r\n" "Starting development server at http://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n") % { "started_at": now, "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading) 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) self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
def inner_run(self, *args, **options): # If an exception was silenced in ManagementUtility.execute in order # to be raised in the child process, raise it now. autoreload.raise_last_exception() threading = options["use_threading"] # 'shutdown_message' is a stealth option. shutdown_message = options.get("shutdown_message", "") quit_command = "CTRL-BREAK" if sys.platform == "win32" else "CONTROL-C" if not options["skip_checks"]: self.stdout.write("Performing system checks...\n\n") self.check(display_num_errors=True) # Need to check migrations here, so can't use the # requires_migrations_check attribute. self.check_migrations() now = datetime.now().strftime("%B %d, %Y - %X") self.stdout.write(now) self.stdout.write( ("Django version %(version)s, using settings %(settings)r\n" "Starting development server at %(protocol)s://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.") % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "protocol": self.protocol, "addr": "[%s]" % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) try: handler = self.get_handler(*args, **options) run( self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls, ) except OSError 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 = e self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
def inner_run(): from django.conf import settings import hotshot, time, os prof_path = options.get('prof_path', '/tmp') def make_profiler_handler(inner_handler): def handler(environ, start_response): path_info = environ['PATH_INFO'] # normally /media/ is MEDIA_URL, but in case still check it in case it's differently # should be hardly a penalty since it's an OR expression. # TODO: fix this to check the configuration settings and not make assumpsions about where media are on the url if no_media and (path_info.startswith('/media') or path_info.startswith(settings.MEDIA_URL)): return inner_handler(environ, start_response) path_name = path_info.strip("/").replace('/', '.') or "root" profname = "%s.%s.prof" % (path_name, datetime.now().isoformat()) profname = os.path.join(prof_path, profname) 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 prof.close() profname2 = "%s_%06dms_%s.prof" % (path_name, elapms, datetime.now().isoformat()) profname2 = os.path.join(prof_path, profname2) def lawl(): time.sleep(0.2) os.spawnlp(os.P_WAIT, "hotshot2calltree", "hotshot2calltree", profname, '-o', profname2) os.unlink(profname) thread.start_new_thread(lawl, ()) return handler 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 "Quit the server with %s." % quit_command try: path = admin_media_path or django.__path__[0] + '/contrib/admin/media' handler = make_profiler_handler(AdminMediaHandler(WSGIHandler(), path)) run(addr, int(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(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)
def inner_run(): from django.conf import settings import hotshot, time, os if options.get('use_cprofile', False): try: import cProfile USE_CPROFILE = True except ImportError: USE_CPROFILE = False else: USE_CPROFILE = False prof_path = options.get('prof_path', '/tmp') def make_profiler_handler(inner_handler): def handler(environ, start_response): path_info = environ['PATH_INFO'] # normally /media/ is MEDIA_URL, but in case still check it in case it's differently # should be hardly a penalty since it's an OR expression. # TODO: fix this to check the configuration settings and not make assumpsions about where media are on the url if no_media and (path_info.startswith('/media') or path_info.startswith(settings.MEDIA_URL)): return inner_handler(environ, start_response) path_name = path_info.strip("/").replace('/', '.') or "root" profname = "%s.%.3f.prof" % (path_name, time.time()) profname = os.path.join(prof_path, profname) if USE_CPROFILE: prof = cProfile.Profile() else: prof = hotshot.Profile(profname) try: return prof.runcall(inner_handler, environ, start_response) finally: if USE_CPROFILE: prof.dump_stats(profname) return handler 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 "Quit the server with %s." % quit_command try: path = admin_media_path or django.__path__[0] + '/contrib/admin/media' handler = make_profiler_handler(AdminMediaHandler(WSGIHandler(), path)) run(addr, int(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(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)
def launch_server_django(host, port, app): """use django's development server, only works for django apps""" if 'DJANGO_SETTINGS_MODULE' not in os.environ: raise ImportError("no django settings module specified") from django.core.servers.basehttp import run logging.info("Starting Django server, listening on port %s", port) run(host, port, app)
def inner_run(self, *args, **options): from django.conf import settings from django.utils import translation threading = options.get('use_threading') shutdown_message = options.get('shutdown_message', '') quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' self.stdout.write("Performing system checks...\n\n") self.validate(display_num_errors=True) try: self.check_migrations() except ImproperlyConfigured: pass now = datetime.now().strftime('%B %d, %Y - %X') if six.PY2: now = now.decode(get_system_encoding()) self.stdout.write(( "%(started_at)s\n" "Django version %(version)s, using settings %(settings)r\n" "Starting development server at http://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n" ) % { "started_at": now, "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading) 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) self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
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 inner_run(self, *args, **options): # If an exception was silenced in ManagementUtility.execute in order # to be raised in the child process, raise it now. autoreload.raise_last_exception() threading = options['use_threading'] # 'shutdown_message' is a stealth option. shutdown_message = options.get('shutdown_message', '') quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' self.stdout.write("Performing system checks...\n\n") self.check(display_num_errors=True) # Need to check migrations here, so can't use the # requires_migrations_check attribute. self.check_migrations() now = datetime.now().strftime('%B %d, %Y - %X') if six.PY2: now = now.decode(get_system_encoding()) self.stdout.write(now) self.stdout.write(( "Django version %(version)s, using settings %(settings)r\n" "Starting development server at %(protocol)s://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n" ) % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "protocol": self.protocol, "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) 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 = force_text(e) self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
def run_wsgi(self, *args, **options): threading = options["use_threading"] handler = self.get_handler(*args, **options) run( self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls, )
def inner_run(self, *args, **options): from django.conf import settings from django.utils import translation threading = options.get('use_threading') shutdown_message = options.get('shutdown_message', '') 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": self._raw_ipv6 and '[%s]' % self.addr or self.addr, "port": self.port, "quit_command": quit_command, }) # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading) except WSGIServerException as 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) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
def inner_run(self, *args, **options): # If an exception was silenced in ManagementUtility.execute in order # to be raised in the child process, raise it now. autoreload.raise_last_exception() threading = options.get('use_threading') shutdown_message = options.get('shutdown_message', '') quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' self.stdout.write("Performing system checks...\n\n") self.check(display_num_errors=True) self.check_migrations() now = datetime.now().strftime('%B %d, %Y - %X') if six.PY2: now = now.decode(get_system_encoding()) self.stdout.write(now) self.stdout.write( ("Django version %(version)s, using settings %(settings)r\n" "Starting development server at http://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n") % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading) 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 = force_text(e) self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
def startWebServer(): print("Starting web server on port %d" % self.port) from django.core.servers.basehttp import run, AdminMediaHandler, WSGIServerException from django.core.handlers.wsgi import WSGIHandler path = django.__path__[0] + '/contrib/admin/media' handler = AdminMediaHandler(WSGIHandler(), path) # even hackier than everything else handler = AdminMediaHandler(handler, settings.MEDIA_ROOT) handler.media_url = settings.MEDIA_URL run('127.0.0.1', self.port, handler)
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 inner_run(self, *args: Any, **options: Any) -> None: # If an exception was silenced in ManagementUtility.execute in order # to be raised in the child process, raise it now. autoreload.raise_last_exception() threading = options['use_threading'] # 'shutdown_message' is a stealth option. shutdown_message = options.get('shutdown_message', '') quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' self.check(display_num_errors=False) # Need to check migrations here, so can't use the # requires_migrations_check attribute. self.check_migrations() self.stdout.write( ("Django process (re)started. Quit the server with %(quit_command)s.\n" ) % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "protocol": self.protocol, "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) 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) self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
def inner_run(self, *args, **options): from django.conf import settings from django.utils import translation threading = options.get('use_threading') shutdown_message = options.get('shutdown_message', '') 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" "Starting development server 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": self._raw_ipv6 and '[%s]' % self.addr or self.addr, "port": self.port, "quit_command": quit_command, }) # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading) except WSGIServerException as 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) self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
def inner_run(self, *args, **options): threading = options.get('use_threading') shutdown_message = options.get('shutdown_message', '') 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.mushroom_port = getattr(settings, 'MUSHROOM_PORT', int(self.port) + 100) self.stdout.write(( "Django version %(version)s, using settings %(settings)r\n" "Development server is running at http://%(addr)s:%(port)s/\n" "Mushroom server is running at http://%(addr)s:%(mushroom_port)s/\n" "Quit the server with %(quit_command)s.\n" ) % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "addr": self._raw_ipv6 and '[%s]' % self.addr or self.addr, "port": self.port, "mushroom_port": self.mushroom_port, "quit_command": quit_command, }) # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: handler = self.get_handler(*args, **options) if not hasattr(self, 'mushroom_server'): self.mushroom_server = _run_mushroom_server( self.addr, self.mushroom_port, settings.INSTALLED_APPS ) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading) 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(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)
def inner_run(): from django.conf import settings from django.utils import translation 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("Quit the server with %s." % quit_command) # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: path = admin_media_path or django.__path__[0] + '/contrib/admin/media' if profile: import hotshot, time, tempfile def make_profiler_handler(inner_handler): def handler(environ, start_response): path = environ['PATH_INFO'].strip("/").replace('/', '.') fd, profname = tempfile.mkstemp('.prof', '%s.%3f' % (path, time.time())) os.close(fd) prof = hotshot.Profile(profname) return prof.runcall(inner_handler, environ, start_response) return handler handler = make_profiler_handler(AdminMediaHandler(WSGIHandler(), path)) else: handler = AdminMediaHandler(WSGIHandler(), path) run(addr, int(port), handler) except WSGIServerException as 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(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(): from django.conf import settings from django.utils import translation 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 "Quit the server with %s." % quit_command # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) # map the Urls to the class application = tornado.web.Application([ (r"/", ListMessagesHandler), (r"/form/", FormHandler), ]) # Start the server if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) tornado.ioloop.IOLoop.instance().start() try: path = admin_media_path or django.__path__[0] + '/contrib/admin/media' handler = AdminMediaHandler(WSGIHandler(), path) run(addr, int(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(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)
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, AdminMediaHandler, 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: handler = AdminMediaHandler(WSGIHandler(), '') 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 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 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 inner_run(): from django.conf.settings import SETTINGS_MODULE print "Validating models..." validate() print "\nStarting server on port %s with settings module %r." % (port, SETTINGS_MODULE) print "Go to http://%s:%s/ for Django." % (addr, port) print "Quit the server with CONTROL-C (Unix) or CTRL-BREAK (Windows)." try: run(addr, int(port), AdminMediaHandler(WSGIHandler())) 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\n" % error_text) sys.exit(1)
def _run(): from django.conf import settings from django.utils import translation print 'Open-in-editor server started' try: run(addr, int(port), WSGIHandler()) 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(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)
def _run(): from django.conf import settings from django.utils import translation print 'Open-in-editor server started' try: run(addr, int(port), WSGIHandler()) 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( 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)
def inner_run(self, *args, **options): # If an exception was silenced in ManagementUtility.execute in order # to be raised in the child process, raise it now. autoreload.raise_last_exception() threading = options['use_threading'] # 'shutdown_message' is a stealth option. shutdown_message = options.get('shutdown_message', '') quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' self.stdout.write("Performing system checks...\n") #======================================================================= # Added by Adam Nieto # Gathering xss suppression file path user_current_directory = os.path.dirname(os.path.abspath(sys.argv[0])) suppression_file_path = os.path.join(user_current_directory, "xss_detector_suppressions.txt") rule_file_path = os.path.join(user_current_directory, "additional_xss_detector_rules.txt") # Checking if xss suppression file should be created if not self.check_suppression_file_exists(suppression_file_path): self.create_suppression_file(suppression_file_path) # Checking if xss rule file should be created if not self.check_rule_file_exists(rule_file_path): self.create_rule_file(rule_file_path) self.stdout.write("Performing xss vulnerability checks...\n\n") xss_warnings_are_silenced = options["silence_xss_warnings"] self.check_xss_vulnerabilities(xss_warnings_are_silenced, suppression_file_path, rule_file_path) #======================================================================= self.check(display_num_errors=True) # Need to check migrations here, so can't use the # requires_migrations_check attribute. self.check_migrations() now = datetime.now().strftime('%B %d, %Y - %X') if six.PY2: now = now.decode(get_system_encoding()) self.stdout.write(now) self.stdout.write( ("Django version %(version)s, using settings %(settings)r\n" "Starting development server at %(protocol)s://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n") % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "protocol": self.protocol, "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) 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 = force_text(e) self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
from rmap.rmapstation import station if __name__ == '__main__': arg = os.getenv('PYTHON_SERVICE_ARGUMENT') print "message from father: ",arg if arg is None: arg="station" if arg == "webserver": from django.core.servers.basehttp import run, get_internal_wsgi_application run("localhost",8888,get_internal_wsgi_application(), ipv6=False, threading=False) if arg == "station": import django django.setup() mystation=station() print "background restored queue:",mystation.anavarlist,mystation.datavarlist mystation.display() mystation.boot() mystation.loopforever()
from rmap.rmapstation import station if __name__ == '__main__': arg = os.getenv('PYTHON_SERVICE_ARGUMENT') print("message from father: ", arg) if arg is None: arg = "station" if arg == "webserver": from django.core.servers.basehttp import run, get_internal_wsgi_application run("127.0.0.1", 8888, get_internal_wsgi_application(), ipv6=False, threading=False) if arg == "station": mystation = station() print("background restored queue:", mystation.anavarlist, mystation.datavarlist) mystation.display() mystation.boot() mystation.loopforever()
def handle(self, *labels, **options): #handler = get_internal_wsgi_application() #django.setup(set_prefix=False) handler = SimpleHandler() #handler = base.BaseHandler() run("127.0.0.1", 8000, handler, ipv6=False, threading=False)
from __future__ import unicode_literals
def inner_run(): import os import time try: import hotshot HAS_HOTSHOT = True except ImportError: HAS_HOTSHOT = False # python 3.x USE_CPROFILE = options['use_cprofile'] USE_LSPROF = options['use_lsprof'] 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_HOTSHOT and not USE_CPROFILE: raise CommandError("Hotshot profile library not found. (and not using cProfile)") prof_path = options['prof_path'] prof_file = options['prof_file'] 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) 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) try: handler = get_internal_wsgi_application() if USE_STATICFILES: use_static_handler = options['use_static_handler'] insecure_serving = options['insecure_serving'] if use_static_handler and (settings.DEBUG or insecure_serving): handler = StaticFilesHandler(handler) handler = make_profiler_handler(handler) run(addr, int(port), handler, threading=options['use_threading']) 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 (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)
# environment variables sys.path.append(MUMBLE_DJANGO_ROOT) sys.path.append(join(MUMBLE_DJANGO_ROOT, 'pyweb')) if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' # parse argv to options OPARSER = OptionParser() OPARSER.add_option("-i", "--ip", dest="addr", default="127.0.0.1") OPARSER.add_option("-p", "--port", dest="port", type="int", default="8080") (OPTIONS, ARGS) = OPARSER.parse_args() try: HANDLER = AdminMediaHandler(WSGIHandler(), '') webbrowser.open('http://%s:%s' % (OPTIONS.addr, OPTIONS.port)) run(OPTIONS.addr, OPTIONS.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 \n" % ERROR_TEXT)
def inner_run(): import os import time import hotshot 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 SystemExit("Kcachegrind compatible output format required cProfile from Python 2.5") 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) kg.output(open(profname, 'w')) 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...") 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 WSGIServerException as 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(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(): from django.conf import settings import os import time import hotshot 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 SystemExit( "Kcachegrind compatible output format required cProfile from Python 2.5" ) prof_path = options.get('prof_path', '/tmp') def make_profiler_handler(inner_handler): def handler(environ, start_response): path_info = environ['PATH_INFO'] # normally /media/ is MEDIA_URL, but in case still check it in case it's differently # should be hardly a penalty since it's an OR expression. # TODO: fix this to check the configuration settings and not make assumpsions about where media are on the url if no_media and (path_info.startswith('/media') or path_info.startswith(settings.MEDIA_URL)): return inner_handler(environ, start_response) path_name = path_info.strip("/").replace('/', '.') or "root" profname = "%s.%s.prof" % (path_name, datetime.now().isoformat()) 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) kg.output(file(profname, 'w')) elif USE_CPROFILE: prof.dump_stats(profname) profname2 = "%s.%06dms.%s.prof" % ( path_name, elapms, datetime.now().isoformat()) profname2 = os.path.join(prof_path, profname2) os.rename(profname, profname2) return handler 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 "Quit the server with %s." % quit_command path = 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 = make_profiler_handler( AdminMediaHandler(WSGIHandler(), path)) run(addr, int(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( 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)
import os import sys path = os.path.split(os.getcwd())[0] sys.path.insert(0, path) sys.stdout = sys.stderr # sys.stdout access restricted by mod_wsgi os.environ['DJANGO_SETTINGS_MODULE'] = 'i2maps.settings' import django.core.handlers.wsgi from django.core.servers.basehttp import run, AdminMediaHandler, WSGIServerException import i2maps.settings as settings settings.DEVELOPMENT = True application = django.core.handlers.wsgi.WSGIHandler() handler = application if len(sys.argv) > 1: addrport = sys.argv[1] addr, port = addrport.split(':') else: addr = '127.0.0.1' port = 8000 quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' print "i2maps development server is running at http://%s:%s/" % (addr, port) print "i2maps library: %s" % (settings.PROJECT_PATH) print "i2maps working directory: %s" % (settings.I2MAPS_WORKING_DIRECTORY) print "Quit the server with %s." % quit_command run(addr, int(port), handler)
def main(): # Check for the database database_file = mathics_settings.DATABASES['default']['NAME'] if not os.path.exists(database_file): print "Error: Mathics database not found!" print "Please change to the mathics install directory and run:\n" print " $> python setup.py initialize\n" print "as the current user" sys.exit(-1) 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 argparser = argparse.ArgumentParser( prog='mathicsserver', usage='%(prog)s [options]', add_help=False, description="""Mathics server for the graphical user interface in a web browser. It is not intended for production use on a public Web server!""", epilog="""Please feel encouraged to contribute to Mathics! Create your own fork, make the desired changes, commit, and make a pull request.""") argparser.add_argument( '--help', '-h', help='show this help message and exit', action='help') argparser.add_argument( '--quiet', '-q', help='don\'t print message at startup', action='store_true') argparser.add_argument( '--version', '-v', action='version', version='%(prog)s ' + mathics.__version__) argparser.add_argument( "--port", "-p", dest="port", metavar="PORT", default=8000, type=int, help="use PORT as server port") argparser.add_argument( "--external", "-e", dest="external", action="store_true", help="allow external access to server") args = argparser.parse_args() quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' port = args.port if not args.quiet: print_version(is_server=True) print_license() print u"Quit by pressing %s\n" % quit_command print u"""Open the graphical user interface at http://localhost:%d\n in Firefox, Chrome, or Safari to use Mathics\n""" % port if args.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 inner_run(self, *args, **options): # If an exception was silenced in ManagementUtility.execute in order # to be raised in the child process, raise it now. import threading ct = threading.current_thread() print( '【django.core.management.commands.runserver.Command.inner_run】当前线程:', ct.name, ct.ident) autoreload.raise_last_exception() threading = options['use_threading'] # 'shutdown_message' is a stealth option. shutdown_message = options.get('shutdown_message', '') quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' #self.stdout.write("Performing system checks...\n\n") self.check(display_num_errors=True) # Need to check migrations here, so can't use the # requires_migrations_check attribute. # 检查数据库版本迁移,需要在终端执行 python manage.py migrate 之类的命令 self.check_migrations() print('【django.core.management.commands.runserver.Command.inner_run】', end='') print( f"Starting development server at {self.protocol}://{self.addr}:{self.port}" ) """ now = datetime.now().strftime('%B %d, %Y - %X') self.stdout.write(now) self.stdout.write(( "Django version %(version)s, using settings %(settings)r\n" "Starting development server at %(protocol)s://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s." ) % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "protocol": self.protocol, "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) """ try: # 这里 self 是「命令处理对象」 # 下面的 handle 是 django.core.handlers.wsgi.WSGIHandler 类的实例 # 此实例就相当于 Flask 中的 app 应用对象 handler = self.get_handler(*args, **options) # 这个 run 方法是核心,定义在 django.core.servers.basehttp 模块中 # 在方法内部会创建服务器对象并启动监听 # 参数 handler 是应用对象,server_cls 是服务器类,其实例就是携带 TCP 套接字的对象 run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) except OSError 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 = e self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
from django.conf import settings import django django.setup() from rmap.rmapstation import station if __name__ == '__main__': arg = os.getenv('PYTHON_SERVICE_ARGUMENT') print "message from father: ",arg if arg is None: arg="station" if arg == "webserver": from django.core.servers.basehttp import run, get_internal_wsgi_application run("127.0.0.1",8888,get_internal_wsgi_application(), ipv6=False, threading=False) if arg == "station": mystation=station() print "background restored queue:",mystation.anavarlist,mystation.datavarlist mystation.display() mystation.boot() mystation.loopforever()
def inner_run(): from django.conf import settings import os import time import hotshot 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 SystemExit("Kcachegrind compatible output format required cProfile from Python 2.5") prof_path = options.get('prof_path', '/tmp') def make_profiler_handler(inner_handler): def handler(environ, start_response): path_info = environ['PATH_INFO'] # normally /media/ is STATIC_URL, but in case still check it in case it's differently # should be hardly a penalty since it's an OR expression. # TODO: fix this to check the configuration settings and not make assumpsions about where media are on the url if no_media and (path_info.startswith('/media') or path_info.startswith(settings.STATIC_URL)): return inner_handler(environ, start_response) path_name = path_info.strip("/").replace('/', '.') or "root" profname = "%s.%s.prof" % (path_name, datetime.now().isoformat()) 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) kg.output(file(profname, 'w')) elif USE_CPROFILE: prof.dump_stats(profname) profname2 = "%s.%06dms.%s.prof" % (path_name, elapms, datetime.now().isoformat()) profname2 = os.path.join(prof_path, profname2) os.rename(profname, profname2) return handler 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 "Quit the server with %s." % quit_command try: path = admin_media_path or django.__path__[0] + '/contrib/admin/media' handler = make_profiler_handler(AdminMediaHandler(WSGIHandler(), path)) run(addr, int(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(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)
def serve(handler, host='localhost', port=6789): from django.core.servers.basehttp import run run(host, int(port), handler)
def inner_run(): from django.conf import settings from django.utils import translation 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 "Quit the server with %s." % quit_command # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: # BEGIN profiling import cProfile import pstats import time import tempfile profile_temp_dir = None if profile_temp_dir is not None: tempfile.tempdir = profile_temp_dir def make_profiler_handler(inner_handler): def handler(environ, start_response): print "============= Starting response ====================" path = environ['PATH_INFO'] if path.startswith(settings.MEDIA_URL): return inner_handler(environ, start_response) path = path.strip('/').replace('/', '.') if path: prefix = 'p.%s.%3f' % (path, time.time()) else: prefix = 'p.%3f' % time.time() fd, profname = tempfile.mkstemp('.prof', prefix) os.close(fd) prof = cProfile.Profile() try: return prof.runcall(inner_handler, environ, start_response) finally: prof.dump_stats(profname) stats = pstats.Stats(profname) stats.sort_stats('cumulative', 'time', 'calls') stats.print_stats('madrona', 20) print " * Complete cProfile output at %s" % profname print "============= Done =================================" return handler # END #handler = AdminMediaHandler(WSGIHandler(), admin_media_path) handler = make_profiler_handler( AdminMediaHandler(WSGIHandler(), admin_media_path)) run(addr, int(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( 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)
def inner_run(): from django.conf import settings from django.utils import translation 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 "Quit the server with %s." % quit_command # django.core.management.base forces the locale to en-us. We should # set it up correctly for the first request (particularly important # in the "--noreload" case). translation.activate(settings.LANGUAGE_CODE) try: # BEGIN profiling import cProfile import pstats import time import tempfile profile_temp_dir = None if profile_temp_dir is not None: tempfile.tempdir = profile_temp_dir def make_profiler_handler(inner_handler): def handler(environ, start_response): print "============= Starting response ====================" path = environ["PATH_INFO"] if path.startswith(settings.MEDIA_URL): return inner_handler(environ, start_response) path = path.strip("/").replace("/", ".") if path: prefix = "p.%s.%3f" % (path, time.time()) else: prefix = "p.%3f" % time.time() fd, profname = tempfile.mkstemp(".prof", prefix) os.close(fd) prof = cProfile.Profile() try: return prof.runcall(inner_handler, environ, start_response) finally: prof.dump_stats(profname) stats = pstats.Stats(profname) stats.sort_stats("cumulative", "time", "calls") stats.print_stats("madrona", 20) print " * Complete cProfile output at %s" % profname print "============= Done =================================" return handler # END # handler = AdminMediaHandler(WSGIHandler(), admin_media_path) handler = make_profiler_handler(AdminMediaHandler(WSGIHandler(), admin_media_path)) run(addr, int(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(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)
def start_server(): with patch('django.core.servers.basehttp.WSGIRequestHandler.log_message'): run('0.0.0.0', 65432, handler, ipv6=False, threading=False)
def main(): # Check for the database database_file = mathics_settings.DATABASES['default']['NAME'] if not os.path.exists(database_file): print("warning: database file %s not found\n" % database_file) import subprocess if not os.path.exists(mathics_settings.DATA_DIR): print("Creating data directory %s" % mathics_settings.DATA_DIR) os.makedirs(mathics_settings.DATA_DIR) print("Creating database %s" % database_file) manage_file = os.path.join( os.path.dirname(os.path.realpath(__file__)), "manage.py") try: subprocess.check_call( [sys.executable, manage_file, 'migrate', '--noinput']) print("\ndatabase initialized sucessfully") except subprocess.CalledProcessError: print("error: failed to create database") sys.exit(1) 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 from django.core.handlers.wsgi import WSGIHandler argparser = argparse.ArgumentParser( prog='mathicsserver', usage='%(prog)s [options]', add_help=False, description="""Mathics server for the graphical user interface in a web browser. It is not intended for production use on a public Web server!""", epilog="""Please feel encouraged to contribute to Mathics! Create your own fork, make the desired changes, commit, and make a pull request.""") argparser.add_argument( '--help', '-h', help='show this help message and exit', action='help') argparser.add_argument( '--quiet', '-q', help='don\'t print message at startup', action='store_true') argparser.add_argument( '--version', '-v', action='version', version='%(prog)s ' + mathics.__version__) argparser.add_argument( "--port", "-p", dest="port", metavar="PORT", default=8000, type=int, help="use PORT as server port") argparser.add_argument( "--external", "-e", dest="external", action="store_true", help="allow external access to server") args = argparser.parse_args() quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' port = args.port if not args.quiet: print_version(is_server=True) print_license() print u"Quit by pressing %s\n" % quit_command print u"""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: 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 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 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 main(): # Check for the database database_file = mathics_settings.DATABASES['default']['NAME'] if not os.path.exists(database_file): print "Error: Mathics database not found!" print "Please change to the mathics install directory and run:\n" print " $> python setup.py initialize\n" print "as the current user" sys.exit(-1) 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 from django.core.handlers.wsgi import WSGIHandler argparser = argparse.ArgumentParser( prog='mathicsserver', usage='%(prog)s [options]', add_help=False, description="""Mathics server for the graphical user interface in a web browser. It is not intended for production use on a public Web server!""", epilog="""Please feel encouraged to contribute to Mathics! Create your own fork, make the desired changes, commit, and make a pull request.""") argparser.add_argument('--help', '-h', help='show this help message and exit', action='help') argparser.add_argument('--quiet', '-q', help='don\'t print message at startup', action='store_true') argparser.add_argument('--version', '-v', action='version', version='%(prog)s ' + mathics.__version__) argparser.add_argument("--port", "-p", dest="port", metavar="PORT", default=8000, type=int, help="use PORT as server port") argparser.add_argument("--external", "-e", dest="external", action="store_true", help="allow external access to server") args = argparser.parse_args() quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' port = args.port if not args.quiet: print_version(is_server=True) print_license() print u"Quit by pressing %s\n" % quit_command print u"""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 = '' 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 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 inner_run(): import os import time import hotshot 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 SystemExit( "Kcachegrind compatible output format required cProfile from Python 2.5" ) prof_path = options.get('prof_path', '/tmp') 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) kg.output(file(profname, 'w')) elif USE_CPROFILE: prof.dump_stats(profname) profname2 = "%s.%06dms.%d.prof" % (path_name, elapms, time.time()) profname2 = os.path.join(prof_path, profname2) if not USE_CPROFILE: prof.close() os.rename(profname, profname2) return handler 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 "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 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( 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)
def run(self): settings.configure(**django_settings) application = get_wsgi_application() run('127.0.0.1', 8080, application)
def inner_run(self, *args, **options): # 非常重要 的 方法 """ self = <django.contrib.staticfiles.management.commands.runserver.Command object at 0x0365E150> :param args: () :param options: 为命令解析 结果 :return: """ # If an exception was silenced in ManagementUtility.execute in order # to be raised in the child process, raise it now. autoreload.raise_last_exception() # 作用不理解 threading = options['use_threading'] # True # 'shutdown_message' is a stealth option. shutdown_message = options.get('shutdown_message', '') # "" quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' # "CTRL-BREAK" self.stdout.write("Performing system checks...\n\n") self.check(display_num_errors=True) # 不理解 # Need to check migrations here, so can't use the # requires_migrations_check attribute. self.check_migrations() # 不理解 now = datetime.now().strftime('%B %d, %Y - %X') self.stdout.write(now) self.stdout.write(( "Django version %(version)s, using settings %(settings)r\n" "Starting development server at %(protocol)s://%(addr)s:%(port)s/\n" "Quit the server with %(quit_command)s.\n" ) % { "version": self.get_version(), "settings": settings.SETTINGS_MODULE, "protocol": self.protocol, "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr, "port": self.port, "quit_command": quit_command, }) try: # 关键代码 handler = self.get_handler(*args, **options) # 返回了 静态文件 句柄 对象 # handler == <django.contrib.staticfiles.handlers.StaticFilesHandler object at 0x000001D13A0C7308> """ 作用: 1. 加载 wsgi.py 中 的 application 2. 解析 静态 ulr, settings.STATIC_URL 3. 加载 中间件 , settings.MIDDLEWARE """ # 关键代码 run(self.addr, int(self.port), handler, # 开启 wsgi Web 服务 ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) 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 = e self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)