def Run(self): # Import modules import cherrypy from cherrypy.wsgiserver import CherryPyWSGIServer from subprocess import call, DEVNULL from win32process import DETACHED_PROCESS, CREATE_NO_WINDOW # Initialize django os.environ.setdefault('DJANGO_SETTINGS_MODULE', "freppledb.settings") os.environ.setdefault('FREPPLE_APP', os.path.join(sys.path[0], 'custom')) import django django.setup() from django.conf import settings from django.core.handlers.wsgi import WSGIHandler from django.contrib.staticfiles.handlers import StaticFilesHandler # Override the debugging settings settings.DEBUG = False settings.TEMPLATE_DEBUG = False # Sys.path contains the zip file with all packages. We need to put the # application directory into the path as well. sys.path += [os.environ['FREPPLE_APP']] # Append all output to a unbuffered log stream with open(os.path.join(settings.FREPPLE_LOGDIR, 'service.log'), 'a') as logfile: sys.stderr = sys.stdout = logfile try: # Using the included postgres database # Check if the database is running. If not, start it. if os.path.exists( os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe')): status = call([ os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe'), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, 'database'), "--silent", "status" ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=CREATE_NO_WINDOW) if status: print("%s\tStarting the PostgreSQL database" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"), flush=True) call([ os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe'), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, 'database'), "--log", os.path.join(settings.FREPPLE_LOGDIR, 'database', 'server.log'), "start" ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=DETACHED_PROCESS) # Prepare web server cherrypy.config.update({ 'global': { 'log.screen': False, 'tools.log_tracebacks.on': True, 'engine.autoreload.on': False, 'engine.SIGHUP': None, 'engine.SIGTERM': None } }) self.server = CherryPyWSGIServer( ('127.0.0.1', settings.PORT), StaticFilesHandler(WSGIHandler())) # Synchronize the scenario table with the settings from freppledb.common.models import Scenario Scenario.syncWithSettings() # Infinite loop serving requests # The loop gets interrupted when the service gets ordered to shut down. print( "%s\tfrePPLe web server listening on http://localhost:%d" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), settings.PORT), flush=True) self.server.start() print("%s\tStopping service" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"), flush=True) # Using the included postgres database? if os.path.exists( os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe')): # Check if the database is running. If so, stop it. os.environ['PATH'] = os.path.join( settings.FREPPLE_HOME, '..', 'pgsql', 'bin') + os.pathsep + os.environ['PATH'] status = call([ os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe'), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, 'database'), "--silent", "status" ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=CREATE_NO_WINDOW) if not status: print("%s\tShutting down the database", datetime.now().strftime("%Y-%m-%d %H:%M:%S"), flush=True) call( [ os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe'), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, 'database'), "--log", os.path.join(settings.FREPPLE_LOGDIR, 'database', 'server.log'), "-w", # Wait till it's down "stop" ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=CREATE_NO_WINDOW) # Notify the manager self.stopEvent.set() except Exception as e: print("%s\tfrePPLe web server failure: %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), e), flush=True)
def get_wsgi_handler(self): return StaticFilesHandler(WSGIHandler())
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) 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(addr, int(port), DebuggedApplication(handler, True), use_reloader=use_reloader, use_debugger=True, threaded=threaded, ssl_context=ssl_context)
# This is necessary to print exceptions occurred in gevent-socketio def exception_printer(sender, **kwArgs): # TODO: Parameterize and/or send to logs print >> sys.stderr, ''.join(traceback.format_exception(*sys.exc_info())) got_request_exception.connect(exception_printer) # Build WSG Application pipeline with django and # the static files handler application = get_wsgi_application() from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler(application) # Start SocketIO server print print 'Django+SocketIO Listening on port %s' % DEFAULT_PORT SocketIOServer( ('', int(DEFAULT_PORT)), application, # Number of seconds between heartbeats server-client. #heartbeat_interval=5, # Number of seconds to wait for a heartbeat. If this # timeout is not met, the connection is considered lost. #heartbeat_timeout=15, resource='socket.io', policy_server=False).serve_forever()
def inner_run(self, options): if not HAS_WERKZEUG: raise CommandError( "Werkzeug is required to use runserver_plus. Please visit http://werkzeug.pocoo.org/ or install via pip. (pip install Werkzeug)" ) # Set colored output if settings.DEBUG: try: set_werkzeug_log_color() except Exception: # We are dealing with some internals, anything could go wrong if self.show_startup_messages: print( "Wrapping internal werkzeug logger for color highlighting has failed!" ) class WSGIRequestHandler(_WSGIRequestHandler): def make_environ(self): environ = super().make_environ() if not options['keep_meta_shutdown_func']: del environ['werkzeug.server.shutdown'] return environ threaded = options['threaded'] use_reloader = options['use_reloader'] open_browser = options['open_browser'] quit_command = 'CONTROL-C' if sys.platform != 'win32' else 'CTRL-BREAK' reloader_interval = options['reloader_interval'] reloader_type = options['reloader_type'] self.extra_files = set(options['extra_files']) self.nopin = options['nopin'] if self.show_startup_messages: print("Performing system checks...\n") try: check_errors( self.check)(display_num_errors=self.show_startup_messages) check_errors(self.check_migrations)() handler = check_errors(self.get_handler)(**options) except Exception as exc: self.stderr.write("Error occurred during checks: %r" % exc, ending="\n\n") handler = self.get_error_handler(exc, **options) 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) if options["cert_path"] or options["key_file_path"]: if not HAS_OPENSSL: raise CommandError( "Python OpenSSL Library is " "required to use runserver_plus with ssl support. " "Install via pip (pip install pyOpenSSL).") certfile, keyfile = self.determine_ssl_files_paths(options) dir_path, root = os.path.split(certfile) root, _ = os.path.splitext(root) try: if os.path.exists(certfile) and os.path.exists(keyfile): ssl_context = (certfile, keyfile) else: # Create cert, key files ourselves. ssl_context = make_ssl_devcert(os.path.join( dir_path, root), host='localhost') except ImportError: if self.show_startup_messages: print( "Werkzeug version is less than 0.9, trying adhoc certificate." ) ssl_context = "adhoc" else: ssl_context = None bind_url = "%s://%s:%s/" % ("https" if ssl_context else "http", self.addr if not self._raw_ipv6 else '[%s]' % self.addr, self.port) if self.show_startup_messages: print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)) print("Development server is running at %s" % (bind_url, )) print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)") print("Quit the server with %s." % quit_command) if open_browser: webbrowser.open(bind_url) if use_reloader and settings.USE_I18N: self.extra_files |= set( filter(lambda filename: str(filename).endswith('.mo'), gen_filenames())) if getattr(settings, 'RUNSERVER_PLUS_EXTRA_FILES', []): self.extra_files |= set(settings['RUNSERVER_PLUS_EXTRA_FILES']) # Werkzeug needs to be clued in its the main instance if running # without reloader or else it won't show key. # https://git.io/vVIgo if not use_reloader: os.environ['WERKZEUG_RUN_MAIN'] = 'true' # Don't run a second instance of the debugger / reloader # See also: https://github.com/django-extensions/django-extensions/issues/832 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': if self.nopin: os.environ['WERKZEUG_DEBUG_PIN'] = 'off' handler = DebuggedApplication(handler, True) runserver_plus_started.send(sender=self) run_simple( self.addr, int(self.port), handler, use_reloader=use_reloader, use_debugger=True, extra_files=self.extra_files, reloader_interval=reloader_interval, reloader_type=reloader_type, threaded=threaded, request_handler=WSGIRequestHandler, ssl_context=ssl_context, )
def inner_run(): # Flag the server as active from devserver import settings import devserver settings.DEVSERVER_ACTIVE = True settings.DEBUG = True 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 "Running django-devserver %s" % (devserver.get_version(), ) if use_werkzeug: server_type = 'werkzeug' else: server_type = 'django' print "%s %s server is running at http://%s:%s/" % ( options['use_forked'] and 'Forked' or 'Threaded', server_type, 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) if int(options['verbosity']) < 1: app = WSGIHandler() else: app = DevServerHandler() if wsgi_app: print "Using WSGI application %r" % wsgi_app if os.path.exists(os.path.abspath(wsgi_app)): # load from file app = imp.load_source( 'wsgi_app', os.path.abspath(wsgi_app)).application else: try: app = __import__(wsgi_app, {}, {}, ['application']).application except (ImportError, AttributeError): raise if options['use_forked']: mixin = SocketServer.ForkingMixIn else: mixin = SocketServer.ThreadingMixIn middleware = getattr(settings, 'DEVSERVER_WSGI_MIDDLEWARE', []) for middleware in middleware: module, class_name = middleware.rsplit('.', 1) app = getattr(__import__(module, {}, {}, [class_name]), class_name)(app) if 'django.contrib.staticfiles' in settings.INSTALLED_APPS and use_static_files: from django.contrib.staticfiles.handlers import StaticFilesHandler app = StaticFilesHandler(app) else: app = AdminMediaHandler(app, admin_media_path) if options['use_dozer']: from dozer import Dozer app = Dozer(app) try: if use_werkzeug: run_simple(addr, int(port), DebuggedApplication(app, True), use_reloader=False, use_debugger=True) else: run(addr, int(port), app, mixin) 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 get_app(self): from django.contrib.staticfiles.handlers import StaticFilesHandler from django.core.handlers.wsgi import WSGIHandler app = StaticFilesHandler(WSGIHandler()) return app
def _twill_setup(): app = StaticFilesHandler(WSGIHandler()) twill.add_wsgi_intercept("127.0.0.1", 8080, lambda: app)
def main(global_settings, **kw): configure(global_settings['__file__']) return StaticFilesHandler(get_wsgi_application())
def run(self): self.lock.acquire() pidfile = os.path.join(tempfile.gettempdir(), 'lettuce-django.pid') if os.path.exists(pidfile): pid = int(open(pidfile).read()) try: os.kill(pid, 9) except OSError: pass finally: os.unlink(pidfile) open(pidfile, 'w').write(unicode(os.getpid())) self.configure_mail_queue() connector = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s = connector.connect((self.address, self.port)) self.lock.release() os.kill(os.getpid(), 9) except socket.error: pass finally: self.lock.release() try: server_address = (self.address, self.port) httpd = WSGIServer(server_address, MutedRequestHandler) except WSGIServerException: raise LettuceServerException( "the port %d already being used, could not start " \ "django's builtin server on it" % self.port, ) handler = WSGIHandler() if self.should_serve_admin_media(): if not AdminMediaHandler: raise LettuceServerException( "AdminMediaHandler is not available in this version of " "Django. Please set LETTUCE_SERVE_ADMIN_MEDIA = False " "in your Django settings.") admin_media_path = '' handler = AdminMediaHandler(handler, admin_media_path) if self.should_serve_static_files(): handler = StaticFilesHandler(handler) httpd.set_app(handler) global keep_running while keep_running: call_hook('before', 'handle_request', httpd, self) httpd.handle_request() call_hook('after', 'handle_request', httpd, self) try: self.lock.release() except ValueError: pass
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 = AdminMediaHandler(WSGIHandler(), 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): # Import modules from cheroot import wsgi from subprocess import call, DEVNULL from win32process import DETACHED_PROCESS, CREATE_NO_WINDOW # Initialize django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "freppledb.settings") os.environ.setdefault("FREPPLE_APP", os.path.join(sys.path[0], "custom")) import django django.setup() from django.conf import settings from django.core.handlers.wsgi import WSGIHandler from django.contrib.staticfiles.handlers import StaticFilesHandler # Override the debugging settings settings.DEBUG = False settings.TEMPLATE_DEBUG = False # Sys.path contains the zip file with all packages. We need to put the # application directory into the path as well. sys.path += [os.environ["FREPPLE_APP"]] # Append all output to a unbuffered log stream with open(os.path.join(settings.FREPPLE_LOGDIR, "service.log"), "a") as logfile: sys.stderr = sys.stdout = logfile try: # Using the included postgres database # Check if the database is running. If not, start it. if os.path.exists( os.path.join(settings.FREPPLE_HOME, "..", "pgsql", "bin", "pg_ctl.exe")): status = call( [ os.path.join( settings.FREPPLE_HOME, "..", "pgsql", "bin", "pg_ctl.exe", ), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, "database"), "--silent", "status", ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=CREATE_NO_WINDOW, ) if status: print( "%s\tStarting the PostgreSQL database" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"), flush=True, ) call( [ os.path.join( settings.FREPPLE_HOME, "..", "pgsql", "bin", "pg_ctl.exe", ), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, "database"), "--log", os.path.join(settings.FREPPLE_LOGDIR, "database", "server.log"), "start", ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=DETACHED_PROCESS, ) # Prepare web server self.server = wsgi.Server((settings.ADDRESS, settings.PORT), StaticFilesHandler(WSGIHandler())) # Synchronize the scenario table with the settings from freppledb.common.models import Scenario Scenario.syncWithSettings() # Infinite loop serving requests # The loop gets interrupted when the service gets ordered to shut down. print( "%s\tfrePPLe web server listening on http://%s:%d" % ( datetime.now().strftime("%Y-%m-%d %H:%M:%S"), settings.ADDRESS, settings.PORT, ), flush=True, ) self.server.start() print( "%s\tStopping service" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"), flush=True, ) # Using the included postgres database? if os.path.exists( os.path.join(settings.FREPPLE_HOME, "..", "pgsql", "bin", "pg_ctl.exe")): # Check if the database is running. If so, stop it. os.environ["PATH"] = (os.path.join(settings.FREPPLE_HOME, "..", "pgsql", "bin") + os.pathsep + os.environ["PATH"]) status = call( [ os.path.join( settings.FREPPLE_HOME, "..", "pgsql", "bin", "pg_ctl.exe", ), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, "database"), "--silent", "status", ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=CREATE_NO_WINDOW, ) if not status: print( "%s\tShutting down the database" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"), flush=True, ) call( [ os.path.join( settings.FREPPLE_HOME, "..", "pgsql", "bin", "pg_ctl.exe", ), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, "database"), "--log", os.path.join(settings.FREPPLE_LOGDIR, "database", "server.log"), "-w", # Wait till it's down "stop", ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=CREATE_NO_WINDOW, ) # Notify the manager self.stopEvent.set() except Exception as e: print( "%s\tfrePPLe web server failure: %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), e), flush=True, )
def handle(self, **options): # Determine the port number if 'port' in options: port = int(options['port'] or settings.PORT) else: port = settings.PORT # Determine the number of threads if 'threads' in options: threads = int(options['threads'] or 25) if threads < 1: raise Exception("Invalid number of threads: %s" % threads) else: threads = 25 # Determine the IP-address to listen on: # - either as command line argument # - either 0.0.0.0 by default, which means all active IPv4 interfaces address = 'address' in options and options['address'] or '0.0.0.0' # Validate the address and port number try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((address, port)) s.close() except socket.error as e: raise Exception("Invalid address '%s' and/or port '%s': %s" % (address, port, e)) # Print a header message hostname = socket.getfqdn() print('Starting frePPLe %s web server\n' % VERSION) print( 'To access the server, point your browser to either of the following URLS:' ) if address == '0.0.0.0': print(' http://%s:%s/' % (hostname, port)) for ip in socket.gethostbyname_ex(socket.gethostname())[2]: print(' http://%s:%s/' % (ip, port)) else: print(' http://%s:%s/' % (address, port)) print( '\nThree users are created by default: "admin", "frepple" and "guest" (the default password is equal to the user name)\n' ) print('Quit the server with CTRL-C.\n') # Start a separate thread that will check for updates # We don't wait for it to finish CheckUpdates().start() # Run the WSGI server server = CherryPyWSGIServer((address, port), StaticFilesHandler(WSGIHandler()), numthreads=threads) # Want SSL support? Just set these attributes apparently, but I haven't tested or verified this # server.ssl_certificate = <filename> # server.ssl_private_key = <filename> try: server.start() except KeyboardInterrupt: server.stop()
def inner_run(self, options): try: from werkzeug import run_simple, DebuggedApplication from werkzeug.serving import WSGIRequestHandler as _WSGIRequestHandler # Set colored output if settings.DEBUG: try: set_werkzeug_log_color() except Exception: # We are dealing with some internals, anything could go wrong if self.show_startup_messages: print("Wrapping internal werkzeug logger for color highlighting has failed!") pass except ImportError: raise CommandError("Werkzeug is required to use runserver_plus. Please visit http://werkzeug.pocoo.org/ or install via pip. (pip install Werkzeug)") class WSGIRequestHandler(_WSGIRequestHandler): def make_environ(self): environ = super(WSGIRequestHandler, self).make_environ() if not options['keep_meta_shutdown_func']: del environ['werkzeug.server.shutdown'] return environ threaded = options['threaded'] use_reloader = options['use_reloader'] open_browser = options['open_browser'] quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' extra_files = options['extra_files'] reloader_interval = options['reloader_interval'] reloader_type = options['reloader_type'] self.nopin = options['nopin'] if self.show_startup_messages: print("Performing system checks...\n") if hasattr(self, 'check'): self.check(display_num_errors=self.show_startup_messages) else: self.validate(display_num_errors=self.show_startup_messages) try: self.check_migrations() except ImproperlyConfigured: pass handler = get_internal_wsgi_application() if USE_STATICFILES: use_static_handler = options['use_static_handler'] insecure_serving = options['insecure_serving'] if use_static_handler and (settings.DEBUG or insecure_serving): handler = StaticFilesHandler(handler) if options["cert_path"] or options["key_file_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).") certfile, keyfile = self.determine_ssl_files_paths(options) dir_path, root = os.path.split(certfile) root, _ = os.path.splitext(root) try: from werkzeug.serving import make_ssl_devcert if os.path.exists(certfile) and os.path.exists(keyfile): ssl_context = (certfile, keyfile) else: # Create cert, key files ourselves. ssl_context = make_ssl_devcert(os.path.join(dir_path, root), host='localhost') except ImportError: if self.show_startup_messages: print("Werkzeug version is less than 0.9, trying adhoc certificate.") ssl_context = "adhoc" else: ssl_context = None bind_url = "%s://%s:%s/" % ( "https" if ssl_context else "http", self.addr if not self._raw_ipv6 else '[%s]' % self.addr, self.port) if self.show_startup_messages: print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)) print("Development server is running at %s" % (bind_url,)) print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)") print("Quit the server with %s." % quit_command) if open_browser: import webbrowser webbrowser.open(bind_url) if use_reloader and settings.USE_I18N: extra_files.extend(filter(lambda filename: str(filename).endswith('.mo'), gen_filenames())) # Werkzeug needs to be clued in its the main instance if running # without reloader or else it won't show key. # https://git.io/vVIgo if not use_reloader: os.environ['WERKZEUG_RUN_MAIN'] = 'true' # Don't run a second instance of the debugger / reloader # See also: https://github.com/django-extensions/django-extensions/issues/832 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': if self.nopin: os.environ['WERKZEUG_DEBUG_PIN'] = 'off' handler = DebuggedApplication(handler, True) run_simple( self.addr, int(self.port), handler, use_reloader=use_reloader, use_debugger=True, extra_files=extra_files, reloader_interval=reloader_interval, reloader_type=reloader_type, threaded=threaded, request_handler=WSGIRequestHandler, ssl_context=ssl_context, )
def get_handler(self): return StaticFilesHandler(get_internal_wsgi_application())
def inner_run(): 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())) run_simple( self.addr, int(self.port), DebuggedApplication(handler, True), use_reloader=use_reloader, use_debugger=True, extra_files=extra_files, reloader_interval=reloader_interval, threaded=threaded, ssl_context=ssl_context, )
def SvcDoRun(self): # Environment settings (which are used in the Django settings file and need # to be updated BEFORE importing the settings) os.environ['DJANGO_SETTINGS_MODULE'] = 'freppledb.settings' os.environ['FREPPLE_APP'] = os.path.join( os.path.split(sys.path[0])[0], 'custom') os.environ['FREPPLE_HOME'] = os.path.abspath( os.path.dirname(sys.argv[0])) # Add the custom directory to the Python path. sys.path = [os.environ['FREPPLE_APP'], sys.path[0]] # Import modules from django.conf import settings import cherrypy from cherrypy.wsgiserver import CherryPyWSGIServer import django from django.core.handlers.wsgi import WSGIHandler from django.contrib.staticfiles.handlers import StaticFilesHandler from stat import S_ISDIR, ST_MODE # Override the debugging settings settings.DEBUG = False settings.TEMPLATE_DEBUG = False # Pick up port and adress try: address = socket.gethostbyname(socket.gethostname()) except: address = '127.0.0.1' port = settings.PORT cherrypy.config.update({ 'global': { 'log.screen': False, 'tools.log_tracebacks.on': True, 'engine.autoreload.on': False, 'engine.SIGHUP': None, 'engine.SIGTERM': None } }) self.server = CherryPyWSGIServer((address, port), StaticFilesHandler(WSGIHandler())) # Redirect all output and log a start event try: log = os.path.join(settings.FREPPLE_LOGDIR, 'service.log') sys.stdout = open(log, 'a', 0) msg = "frePPLe web server listening on http://%s:%d and logging to %s" % ( address, port, log) servicemanager.LogInfoMsg(msg) print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg) except: # Too bad if we can't write log info servicemanager.LogInfoMsg( "frePPLe web server listening on http://%s:%d without log file" % (address, port)) # Log usage from freppledb.execute.management.commands.frepple_runserver import CheckUpdates CheckUpdates().start() # Infinite loop serving requests try: self.server.start() except Exception as e: # Log an error event msg = "frePPLe web server failed to start:\n%s" % e servicemanager.LogErrorMsg(msg) print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg)
def inner_run(): import os import time try: import hotshot HAS_HOTSHOT = True except ImportError: HAS_HOTSHOT = 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_HOTSHOT and not USE_CPROFILE: raise CommandError( "Hotshot 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) 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.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, threading=options.get('use_threading', True)) 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)
def get_handler(self, *args, **options): handler = super().get_handler(*args, **options) if self.serve_static: handler = StaticFilesHandler(handler) return handler
""" WSGI config for Empath_FA project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.conf import settings from django.contrib.staticfiles.handlers import StaticFilesHandler from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Empath_FA.settings') if settings.DEBUG: application = StaticFilesHandler(get_wsgi_application()) else: application = get_wsgi_application()
def handle(self, *args, **options): if settings.DEBUG: logger.setLevel(logging.DEBUG) if len(args) > 1: raise CommandError('Usage is runserver_tornadio2 %s' % self.args) if len(args) == 1: if ':' in args[0]: addr, port = args[0].split(':') else: port = args[0] else: port = getattr(settings, 'SOCKETIO_PORT', 8000) # Setup event handlers for Cls in load_classes(getattr(settings,'SOCKETIO_CLASSES', [])): mixin(BaseSocket, Cls) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') wsgi_app = get_wsgi_application() app_handler = WSGIContainer(StaticFilesHandler(wsgi_app)) router = TornadioRouter(BaseSocket, { 'enabled_protocols': [ 'websocket', 'xhr-polling', 'htmlfile' ]}) if not hasattr(settings, 'SOCKETIO_GLOBALS'): settings.SOCKETIO_GLOBALS = {} settings.SOCKETIO_GLOBALS['server'] = router.urls[0][2]['server'] # A map of user IDs to their active connections. settings.SOCKETIO_GLOBALS['connections'] = defaultdict(set) tornado_routes = [] for url, path in getattr(settings, 'SOCKETIO_ROUTES', []): cls = _get_class(path, object) tornado_routes.append((url, cls)) application = Application( router.urls + tornado_routes + [ # Uncomment next line to handle static files through Tornado rather than Django or externally. #(r'/static/(.*)', StaticFileHandler, {'path': settings.STATICFILES_DIRS[0]}), #(r'/admin$', RedirectHandler, {'url': '/admin/', 'permanent': True}), # You probably want to comment out the next line if you have a login form. #(r'/accounts/login/.*', RedirectHandler, {'url': '/admin/', 'permanent': False}), (r'.*', FallbackHandler, {'fallback': app_handler}), ], #flash_policy_port = 843, #flash_policy_file = 'flashpolicy.xml', # TODO: Do we need this? TAA - 2012-03-07. socket_io_port = port, xsrf_cookies = False, debug = settings.DEBUG ) ssl_options = getattr(settings, 'SOCKETIO_SSL_OPTIONS', {}) if ssl_options: SocketServer(application, ssl_options = ssl_options) else: SocketServer(application)