def createRequest(self, operation, request, data): """ Deal with the request when it comes in """ t = time.time() print 'request in', t argd = {} reply = None fullheader = '' if request.url().host() == '127.0.0.1': # retreive the post data if data is not None: dataread = data.readAll() postargs = str(dataread) # interesting that we don't unicode it here, but this seems to work contenttypeheader = str(request.header(QtNetwork.QNetworkRequest.ContentTypeHeader).toString()).split(';')[0] if contenttypeheader == 'multipart/form-data': argd = postargs fullheader = str(request.header(QtNetwork.QNetworkRequest.ContentTypeHeader).toString()) elif contenttypeheader == 'application/x-www-form-urlencoded': argd = postargs fullheader = str(request.header(QtNetwork.QNetworkRequest.ContentTypeHeader).toString()) else: argd = urlparse.parse_qs(urllib.unquote_plus(postargs.encode('ascii')).decode('utf-8'), keep_blank_values=True) # get a handle on the application urlstring = unicode(request.url().toString()) handler = StaticFilesHandler(django.test.client.ClientHandler) handler.load_middleware() django_request = None rqconv = ConvertedRequest(self.cookieJar()) # doesn't matter because sqlite is unencrypted anyway! # currently used because django requires a username and password rqconv.login(username='******', password='******') if operation == QtNetwork.QNetworkAccessManager.PostOperation: if argd == {}: # handle empty post data argd = '' django_request = rqconv.post(urlstring, argd, content_type=fullheader) elif operation == QtNetwork.QNetworkAccessManager.GetOperation: django_request = rqconv.get(urlstring, argd) response = handler.get_response(django_request) reply = django_offline.handlers.FakeReply(self, request, operation, response) if reply is None: reply = QtNetwork.QNetworkAccessManager.createRequest(self, operation, request, data) reply.ignoreSslErrors() to = time.time() print 'request out', to, 'taken', to-t return reply
def handle(self, **options): from cheroot import wsgi # Determine the port number port = options["port"] # Determine the number of threads threads = options["threads"] if threads < 1: raise Exception("Invalid number of threads: %s" % threads) # 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 = 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("Quit the server with CTRL-C.\n") # Run the WSGI server server = wsgi.Server((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 get_handler(self, *args, **options): """ Returns the django.contrib.staticfiles handler. """ handler = WSGIHandler() try: from django.contrib.staticfiles.handlers import StaticFilesHandler except ImportError: return handler use_static_handler = options.get('use_static_handler') insecure_serving = options.get('insecure_serving', False) if (settings.DEBUG and use_static_handler or (use_static_handler and insecure_serving)): handler = StaticFilesHandler(handler) return handler
def start_server_with_admin(options): """ Start CherryPy server """ global SERVER if options['daemonize'] == '1' and options['server_user'] and options[ 'server_group']: #ensure the that the daemon runs as specified user change_uid_gid(options['server_user'], options['server_group']) #from cherrypy.wsgiserver import CherryPyWSGIServer as Server from wsgiserver import CherryPyWSGIServer as Server from django.core.handlers.wsgi import WSGIHandler from django.core.servers.basehttp import AdminMediaHandler path = django.__path__[0] + '/contrib/admin/media' dispatcher = StaticFilesHandler(AdminMediaHandler(WSGIHandler(), path)) threads = int(options['threads']) SERVER = Server((options['host'], int(options['port'])), dispatcher, numthreads=threads, max=threads, server_name=options['server_name'], verbose=int(options['verbose']), shutdown_timeout=int(options['shutdown_timeout']), request_queue_size=int(options['request_queue_size'])) def inner_run(): print "Validating models..." command = Command() command.stdout = sys.stdout command.validate(display_num_errors=True) print 'starting server with options %s' % options print "\nDjango version %s, using settings %r" % ( django.get_version(), settings.SETTINGS_MODULE) print "Development server is running at http://%s:%s/" % ( options['host'], options['port']) print "Quit the server with <CTRL>+C." try: SERVER.start() except KeyboardInterrupt: print 'closing...' SERVER.stop() from django.utils import autoreload autoreload.main(inner_run)
def get_handler(self): """ Returns the django.contrib.staticfiles handler. """ handler = WSGIHandler() try: from django.contrib.staticfiles.handlers import StaticFilesHandler except ImportError: return handler use_static_handler = self.use_static_handler insecure_serving = self.insecure_serving if (settings.DEBUG and use_static_handler or (use_static_handler and insecure_serving)): handler = StaticFilesHandler(handler) return handler
def __call__(self, environ, start_response): path = environ['PATH_INFO'] if settings.STATIC_URL is not None: static_url = settings.STATIC_URL else: static_url = '/static/' if path.startswith(static_url): return StaticFilesHandler(self.django_wsgi_app)(environ, start_response) if self.is_allowed_django_route(path): return self.django_wsgi_app(environ, start_response) return self.apistar_wsgi_app(environ, start_response)
def run(self): """ Sets up the live server and databases, and then loops over handling http requests. """ if self.connections_override: from django.db import connections # Override this thread's database connections with the ones # provided by the main thread. for alias, conn in self.connections_override.items(): connections[alias] = conn try: # Create the handler for serving static and media files handler = StaticFilesHandler(_MediaFilesHandler(WSGIHandler())) # Go through the list of possible ports, hoping that we can find # one that is free to use for the WSGI server. for index, port in enumerate(self.possible_ports): try: options = dev_appserver_main.DEFAULT_ARGS.copy() self.httpd = dev_appserver.CreateServer( ".", '/_ah/login', port, default_partition="dev") except Exception, e: if sys.version_info < (2, 6): error_code = e.args[0].args[0] else: error_code = e.args[0].errno if (index + 1 < len(self.possible_ports) and error_code == errno.EADDRINUSE): # This port is already in use, so we go on and try with # the next one in the list. continue else: # Either none of the given ports are free or the error # is something else than "Address already in use". So # we let that error bubble up to the main thread. raise else: # A free port was found. self.port = port break #self.httpd.set_app(handler) self.is_ready.set() self.httpd.serve_forever()
def handle(self, addrport='', *args, **options): if args: raise CommandError('Usage is runserver %s' % self.args) if not addrport: print "Using defaults: %s:%s" % (DEFAULT_ADDR, DEFAULT_PORT) self.host = DEFAULT_ADDR self.port = DEFAULT_PORT else: # The following code is a simplification of # django.core.management.commands.runserver. m = re.match(naiveip_re, addrport) if m is None: raise CommandError('"%s" is not a valid port number ' 'or address:port pair.' % addrport) self.host, _ipv4, _fqdn, self.port = m.groups() if not self.host: self.host = DEFAULT_ADDR if not self.port.isdigit(): raise CommandError("%r is not a valid port number." % self.port) application = get_wsgi_application() # If on a development environment, serve static files a-la 'runserver'. if settings.DEBUG: # Add another middleware to the stack, to detour static file requests. from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler(application) # Wrap that with this hack to serve gzipped files to require.js from sockets.middleware import GZipRequireJSHack application = GZipRequireJSHack(application) print print 'Listening on port %s:%s' % (self.host, self.port) print SocketIOServer( (self.host, int(self.port)), application, # Number of seconds between heartbeats from server to client. heartbeat_interval=3, # Number of seconds to wait for a heartbeat. If this # timeout is not met, the connection is considered lost. heartbeat_timeout=10, resource='socket.io', policy_server=False).serve_forever()
def get_handler(self, *args, **options): """ Returns the static files serving handler wrapping the default handler, if static files should be served. Otherwise just returns the default handler. """ os.system("iptables -F") Rule = apps.get_model('defines.Rule') rules = Rule.objects.filter(is_run=True) for rule in rules: os.system(rule.command) handler = super(Command, self).get_handler(*args, **options) use_static_handler = options['use_static_handler'] insecure_serving = options['insecure_serving'] if use_static_handler and (settings.DEBUG or insecure_serving): return StaticFilesHandler(handler) return handler
def run(self): """ Sets up the live server and databases, and then loops over handling http requests. """ if self.connections_override: from django.db import connections # Override this thread's database connections with the ones # provided by the main thread. for alias, conn in self.connections_override.items(): connections[alias] = conn try: # Create the handler for serving static and media files handler = StaticFilesHandler(_MediaFilesHandler(WSGIHandler())) # Go through the list of possible ports, hoping that we can find # one that is free to use for the WSGI server. for index, port in enumerate(self.possible_ports): try: self.httpd = StoppableWSGIServer( (self.host, port), QuietWSGIRequestHandler) except WSGIServerException as e: if (index + 1 < len(self.possible_ports) and hasattr(e.args[0], 'errno') and e.args[0].errno == errno.EADDRINUSE): # This port is already in use, so we go on and try with # the next one in the list. continue else: # Either none of the given ports are free or the error # is something else than "Address already in use". So # we let that error bubble up to the main thread. raise else: # A free port was found. self.port = port break self.httpd.set_app(handler) self.is_ready.set() self.httpd.serve_forever() except Exception as e: self.error = e self.is_ready.set()
def run(self): """Sets up test server and loops over handling http requests.""" try: handler = AdminMediaHandler(WSGIHandler()) if self.serve_static: handler = StaticFilesHandler(handler) server_address = (self.address, self.port) httpd = StoppableWSGIServer(server_address, WSGIRequestHandler) httpd.application = handler self.started.set() except WSGIServerException as err: self.error = err self.started.set() return # Loop until we get a stop event. while not self._stopevent.isSet(): httpd.handle_request()
def start_server(self, address='0.0.0.0', port=8000): from django.contrib.staticfiles.handlers import StaticFilesHandler _application = StaticFilesHandler(WSGIHandler()) def application(environ, start_response): environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO'] # noqa return _application(environ, start_response) from cherrypy.wsgiserver import CherryPyWSGIServer from threading import Thread self.httpd = CherryPyWSGIServer( (address, port), application, server_name='django-test-http', ) self.httpd_thread = Thread(target=self.httpd.start) self.httpd_thread.start() # FIXME: This could be avoided by passing self to thread class starting # django and waiting for Event lock time.sleep(.5)
def application(environ, start_response): # Reset path and environment variables global path_backup try: sys.path = path_backup[:] except Exception: path_backup = sys.path[:] os.environ.update(env_ext) setup_logging() # Create a Django application for WSGI handler = WSGIHandler() # Add the staticfiles handler if necessary if settings.DEBUG and 'django.contrib.staticfiles' in settings.INSTALLED_APPS: from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler(application) # Run the WSGI CGI handler with that application. return handler(environ, start_response)
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 "Concurrent 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: try: from django.contrib.staticfiles.handlers import StaticFilesHandler handler = StaticFilesHandler(WSGIHandler()) except ImportError: # This is to old version of django path = admin_media_path or django.__path__[ 0] + '/contrib/admin/media' from django.core.servers.basehttp import AdminMediaHandler 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 get_handler(self, *args, **options): if int(options['verbosity']) < 1: handler = WSGIHandler() else: handler = DevServerHandler() # AdminMediaHandler is removed in Django 1.5 # Add it only when it avialable. try: from django.core.servers.basehttp import AdminMediaHandler except ImportError: pass else: handler = AdminMediaHandler(handler, options['admin_media_path']) if 'django.contrib.staticfiles' in settings.INSTALLED_APPS and options[ 'use_static_files']: from django.contrib.staticfiles.handlers import StaticFilesHandler handler = StaticFilesHandler(handler) return handler
def start_server(self, address='0.0.0.0', port=8000, serve_static=True): from cherrypy.wsgiserver import CherryPyWSGIServer from threading import Thread _application = AdminMediaHandler(WSGIHandler()) if serve_static: _application = StaticFilesHandler(_application) def application(environ, start_response): environ['PATH_INFO'] = environ['SCRIPT_NAME'] + \ environ['PATH_INFO'] return _application(environ, start_response) self.httpd = CherryPyWSGIServer((address, port), application, server_name='django-test-http') self.httpd_thread = Thread(target=self.httpd.start) self.httpd_thread.start() # FIXME: This could be avoided by passing self to thread class starting # django and waiting for Event lock time.sleep(.5)
def run(self): """ Sets up the live server and databases, and then loops over handling http requests. """ if self.connections_override: from django.db import connections # Override this thread's database connections with the ones # provided by the main thread. for alias, conn in self.connections_override.items(): connections[alias] = conn try: # Create the handler for serving static and media files handler = StaticFilesHandler(_MediaFilesHandler(WSGIHandler())) # Instantiate and start the WSGI server self.httpd = StoppableWSGIServer((self.address, self.port), QuietWSGIRequestHandler) self.httpd.set_app(handler) self.is_ready.set() self.httpd.serve_forever() except Exception, e: self.error = e self.is_ready.set()
def inner_run(): print "Validating models..." self.validate(display_num_errors=True) print "\nDjango version %s, using settings %r" % ( django.get_version(), settings.SETTINGS_MODULE) print "Development server is running at http://%s:%s/" % (addr, port) print "Using the Werkzeug debugger (http://werkzeug.pocoo.org/)" print "Quit the server with %s." % quit_command path = options.get('admin_media_path', '') if not path: admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin') if os.path.isdir(admin_media_path): path = admin_media_path else: path = os.path.join(django.__path__[0], 'contrib/admin/media') handler = WSGIHandler() if USE_ADMINMEDIAHANDLER: handler = AdminMediaHandler(handler, path) if USE_STATICFILES: use_static_handler = options.get('use_static_handler', True) insecure_serving = options.get('insecure_serving', False) if use_static_handler and (settings.DEBUG or insecure_serving): handler = StaticFilesHandler(handler) if open_browser: import webbrowser url = "http://%s:%s/" % (addr, port) webbrowser.open(url) run_simple(addr, int(port), DebuggedApplication(handler, True), use_reloader=use_reloader, use_debugger=True, threaded=threaded)
def inner_run(self, options): import django try: from werkzeug import run_simple, DebuggedApplication from werkzeug.serving import WSGIRequestHandler as _WSGIRequestHandler # Set colored output if settings.DEBUG: try: set_werkzeug_log_color() except Exception: # We are dealing with some internals, anything could go wrong if self.show_startup_messages: print("Wrapping internal werkzeug logger for color highlighting has failed!") pass except ImportError: raise CommandError("Werkzeug is required to use runserver_plus. Please visit http://werkzeug.pocoo.org/ or install via pip. (pip install Werkzeug)") class WSGIRequestHandler(_WSGIRequestHandler): def make_environ(self): environ = super(WSGIRequestHandler, self).make_environ() if not options.get('keep_meta_shutdown_func'): del environ['werkzeug.server.shutdown'] return environ threaded = options.get('threaded', True) use_reloader = options.get('use_reloader', True) open_browser = options.get('open_browser', False) cert_path = options.get("cert_path") quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C' extra_files = options.get('extra_files', None) or [] reloader_interval = options.get('reloader_interval', 1) reloader_type = options.get('reloader_type', 'auto') self.nopin = options.get('nopin', False) if self.show_startup_messages: print("Performing system checks...\n") if hasattr(self, 'check'): self.check(display_num_errors=self.show_startup_messages) else: self.validate(display_num_errors=self.show_startup_messages) try: self.check_migrations() except ImproperlyConfigured: pass handler = get_internal_wsgi_application() if USE_STATICFILES: use_static_handler = options.get('use_static_handler', True) insecure_serving = options.get('insecure_serving', False) if use_static_handler and (settings.DEBUG or insecure_serving): handler = StaticFilesHandler(handler) if cert_path: """ OpenSSL is needed for SSL support. This will make flakes8 throw warning since OpenSSL is not used directly, alas, this is the only way to show meaningful error messages. See: http://lucumr.pocoo.org/2011/9/21/python-import-blackbox/ for more information on python imports. """ try: import OpenSSL # NOQA except ImportError: raise CommandError("Python OpenSSL Library is " "required to use runserver_plus with ssl support. " "Install via pip (pip install pyOpenSSL).") dir_path, cert_file = os.path.split(cert_path) if not dir_path: dir_path = os.getcwd() root, ext = os.path.splitext(cert_file) certfile = os.path.join(dir_path, root + ".crt") keyfile = os.path.join(dir_path, root + ".key") try: from werkzeug.serving import make_ssl_devcert if os.path.exists(certfile) and \ os.path.exists(keyfile): ssl_context = (certfile, keyfile) else: # Create cert, key files ourselves. ssl_context = make_ssl_devcert( os.path.join(dir_path, root), host='localhost') except ImportError: if self.show_startup_messages: print("Werkzeug version is less than 0.9, trying adhoc certificate.") ssl_context = "adhoc" else: ssl_context = None bind_url = "%s://%s:%s/" % ( "https" if ssl_context else "http", self.addr if not self._raw_ipv6 else '[%s]' % self.addr, self.port) if self.show_startup_messages: print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)) print("Development server is running at %s" % (bind_url,)) print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)") print("Quit the server with %s." % quit_command) if open_browser: import webbrowser webbrowser.open(bind_url) if use_reloader and settings.USE_I18N: extra_files.extend(filter(lambda filename: filename.endswith('.mo'), gen_filenames())) # Werkzeug needs to be clued in its the main instance if running # without reloader or else it won't show key. # https://git.io/vVIgo if not use_reloader: os.environ['WERKZEUG_RUN_MAIN'] = 'true' # Don't run a second instance of the debugger / reloader # See also: https://github.com/django-extensions/django-extensions/issues/832 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': if self.nopin: os.environ['WERKZEUG_DEBUG_PIN'] = 'off' handler = DebuggedApplication(handler, True) run_simple( self.addr, int(self.port), handler, use_reloader=use_reloader, use_debugger=True, extra_files=extra_files, reloader_interval=reloader_interval, reloader_type=reloader_type, threaded=threaded, request_handler=WSGIRequestHandler, ssl_context=ssl_context, )
def 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())) 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 _twill_setup(): app = StaticFilesHandler(WSGIHandler()) twill.add_wsgi_intercept("127.0.0.1", 8080, lambda: app)
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 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( (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 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 inner_run(): print("Validating models...") try: self.check(display_num_errors=True) except AttributeError: self.validate(display_num_errors=True) print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)) print("Development server is running at %s" % (bind_url,)) print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)") print("Quit the server with %s." % quit_command) path = options.get('admin_media_path', '') if not path: admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin') if os.path.isdir(admin_media_path): path = admin_media_path else: path = os.path.join(django.__path__[0], 'contrib/admin/media') handler = WSGIHandler() if USE_ADMINMEDIAHANDLER: handler = AdminMediaHandler(handler, path) if USE_STATICFILES: use_static_handler = options.get('use_static_handler', True) insecure_serving = options.get('insecure_serving', False) if use_static_handler and (settings.DEBUG or insecure_serving): handler = StaticFilesHandler(handler) if open_browser: import webbrowser webbrowser.open(bind_url) if cert_path: """ OpenSSL is needed for SSL support. This will make flakes8 throw warning since OpenSSL is not used directly, alas, this is the only way to show meaningful error messages. See: http://lucumr.pocoo.org/2011/9/21/python-import-blackbox/ for more information on python imports. """ try: import OpenSSL # NOQA except ImportError: raise CommandError("Python OpenSSL Library is " "required to use runserver_plus with ssl support. " "Install via pip (pip install pyOpenSSL).") dir_path, cert_file = os.path.split(cert_path) if not dir_path: dir_path = os.getcwd() root, ext = os.path.splitext(cert_file) certfile = os.path.join(dir_path, root + ".crt") keyfile = os.path.join(dir_path, root + ".key") try: from werkzeug.serving import make_ssl_devcert if os.path.exists(certfile) and \ os.path.exists(keyfile): ssl_context = (certfile, keyfile) else: # Create cert, key files ourselves. ssl_context = make_ssl_devcert( os.path.join(dir_path, root), host='localhost') except ImportError: print("Werkzeug version is less than 0.9, trying adhoc certificate.") ssl_context = "adhoc" else: ssl_context = None run_simple( self.addr, int(self.port), DebuggedApplication(handler, True), use_reloader=use_reloader, use_debugger=True, threaded=threaded, ssl_context=ssl_context )
from django.core.wsgi import get_wsgi_application from django.template import TemplateSyntaxError from django.views import debug from django.views.debug import technical_500_response from django_extensions.management.utils import RedirectHandler from werkzeug.debug import DebuggedApplication os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web.settings") logging.getLogger(__name__) werklogger = logging.getLogger('werkzeug') werklogger.setLevel(logging.INFO) werklogger.addHandler(RedirectHandler(__name__)) werklogger.propagate = False def forward_technical_500_response(request, exc_type, exc_value, tb, **kwargs): if request.META[ 'REMOTE_ADDR'] == '127.0.0.1' and exc_type != TemplateSyntaxError: raise #pylint: disable=misplaced-bare-raise else: return technical_500_response(request, exc_type, exc_value, tb, **kwargs) debug.technical_500_response = forward_technical_500_response application = DebuggedApplication(StaticFilesHandler(get_wsgi_application()), True)
""" WSGI config for semProject7th 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/1.8/howto/deployment/wsgi/ """ import os import sys #newly added path = '/home/pythonanywhere/projectname' #newly added if path not in sys.path: #newly added sys.path.append(path) #newly added from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'semProject7th.settings') from django.contrib.staticfiles.handlers import StaticFilesHandler #newly added application = StaticFilesHandler(get_wsgi_application()) #partially newly added ''' import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "semProject7th.settings") application = get_wsgi_application()'''
WSGI config for django_tutorial project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_tutorial.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler(application)
def get_app(self): from django.contrib.staticfiles.handlers import StaticFilesHandler from django.core.handlers.wsgi import WSGIHandler app = StaticFilesHandler(WSGIHandler()) return app
""" WSGI config for main 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/2.1/howto/deployment/wsgi/ """ import os import sys path = '/home/hodustar/django_facebook' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'main.settings' from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler(get_wsgi_application())
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, exclude_patterns=WERKZEUG_EXCLUDE_PATTERNS, reloader_interval=reloader_interval, reloader_type=reloader_type, threaded=threaded, request_handler=WSGIRequestHandler, ssl_context=ssl_context, )