def start(): ''' Server loop here. Started in a multiprocess. ''' root = API(__opts__) conf = root.get_conf() gconf = conf.get('global', {}) cherrypy.tools.salt_token = cherrypy.Tool('on_start_resource', salt_token_tool, priority=55) cherrypy.tools.salt_auth = cherrypy.Tool('before_request_body', salt_auth_tool, priority=60) cherrypy.tools.hypermedia_out = cherrypy.Tool('before_handler', hypermedia_out) cherrypy.tools.hypermedia_in = cherrypy.Tool('before_request_body', hypermedia_in) if gconf['debug']: cherrypy.quickstart(root, '/', conf) else: root.verify_certs(gconf['ssl_crt'], gconf['ssl_key']) app = cherrypy.tree.mount(root, '/', config=conf) ssl_a = wsgiserver.ssl_builtin.BuiltinSSLAdapter( gconf['ssl_crt'], gconf['ssl_key']) wsgi_d = wsgiserver.WSGIPathInfoDispatcher({'/': app}) server = wsgiserver.CherryPyWSGIServer( ('0.0.0.0', gconf['server.socket_port']), wsgi_app=wsgi_d) server.ssl_adapter = ssl_a signal.signal(signal.SIGINT, lambda *args: server.stop()) server.start()
def main(): server_type = "werkzeug" if not config.debug_mode: server_type = "cherrypy" if config.web_server_type: server_type = config.web_server_type assert server_type in ("werkzeug", "cherrypy"), "Only werkzeug and cherrypy supported" if server_type == "werkzeug": assert config.debug_mode, "Refusing to use werkzeug outside of debug mode" app.run(config.web_host, config.web_port, debug=True, use_reloader=False, use_debugger=True, threaded=True) elif server_type == "cherrypy": dispatcher = wsgiserver.WSGIPathInfoDispatcher({"/": app}) web_server = wsgiserver.CherryPyWSGIServer( (config.web_host, config.web_port), dispatcher, server_name=config.web_public_host) web_server.start()
def SvcDoRun(self): key = winreg.OpenKey(rootkey, subkey, 0, winreg.KEY_READ) port_to_bind = int(winreg.QueryValueEx(key, 'Port')[0]) data_dir = str(winreg.QueryValueEx(key, 'DataDir')[0]) app_config = data_dir + r'\mapproxy.yaml' log_conf = data_dir + r'\log.ini' cherrypy.config.update({ 'global': { 'log.screen': False, 'tools.log_tracebacks.on': True, 'engine.autoreload.on': False, 'engine.SIGHUP': None, 'engine.SIGTERM': None } }) fileConfig(log_conf, {'here': data_dir}) application = make_wsgi_app(app_config) d = wsgiserver.WSGIPathInfoDispatcher({'/mapproxy': application}) self.server = wsgiserver.CherryPyWSGIServer((server_ip, port_to_bind), d, numthreads=10, server_name=None, max=-1, request_queue_size=2048, timeout=10, shutdown_timeout=5) # Infinite loop serving requests try: self.server.start() except Exception as e: # Log an error event servicemanager.LogErrorMsg("MapProxy failed to start:\n%s" % e)
def start(): #NOTE bots is always on PYTHONPATH!!! - otherwise it will not start. #***command line arguments************************** configdir = 'config' for arg in sys.argv[1:]: if not arg: continue if arg.startswith('-c'): configdir = arg[2:] if not configdir: print 'Configuration directory indicated, but no directory name.' sys.exit(1) elif arg in ["?", "/?"] or arg.startswith('-'): showusage() else: showusage() #***init general: find locating of bots, configfiles, init paths etc.*********************** botsinit.generalinit(configdir) #***initialise logging. This logging only contains the logging from bots-webserver, not from cherrypy. botsglobal.logger = logging.getLogger('bots-webserver') botsglobal.logger.setLevel(logging.DEBUG) h = TimedRotatingFileHandler(botslib.join(botsglobal.ini.get('directories','logging'),'webserver.log'), backupCount=10) fileformat = logging.Formatter("%(asctime)s %(levelname)-8s: %(message)s",'%Y%m%d %H:%M:%S') h.setFormatter(fileformat) botsglobal.logger.addHandler(h) #***init cherrypy as webserver********************************************* #global configuration for cherrypy cherrypy.config.update({'global': {'log.screen': False, 'server.environment': botsglobal.ini.get('webserver','environment','production')}}) #cherrypy handling of static files conf = {'/': {'tools.staticdir.on' : True,'tools.staticdir.dir' : 'media' ,'tools.staticdir.root': botsglobal.ini.get('directories','botspath')}} servestaticfiles = cherrypy.tree.mount(None, '/media', conf) #None: no cherrypy application (as this only serves static files) #cherrypy handling of django servedjango = WSGIHandler() #was: servedjango = AdminMediaHandler(WSGIHandler()) but django does not need the AdminMediaHandler in this setup. is much faster. #cherrypy uses a dispatcher in order to handle the serving of static files and django. dispatcher = wsgiserver.WSGIPathInfoDispatcher({'/': servedjango, '/media': servestaticfiles}) botswebserver = wsgiserver.CherryPyWSGIServer(bind_addr=('0.0.0.0', botsglobal.ini.getint('webserver','port',8080)), wsgi_app=dispatcher, server_name=botsglobal.ini.get('webserver','name','bots-webserver')) botsglobal.logger.info(_(u'Bots web-server started.')) #handle ssl: cherrypy < 3.2 always uses pyOpenssl. cherrypy >= 3.2 uses python buildin ssl (python >= 2.6 has buildin support for ssl). ssl_certificate = botsglobal.ini.get('webserver','ssl_certificate',None) ssl_private_key = botsglobal.ini.get('webserver','ssl_private_key',None) if ssl_certificate and ssl_private_key: if cherrypy.__version__ >= '3.2.0': adapter_class = wsgiserver.get_ssl_adapter_class('builtin') botswebserver.ssl_adapter = adapter_class(ssl_certificate,ssl_private_key) else: #but: pyOpenssl should be there! botswebserver.ssl_certificate = ssl_certificate botswebserver.ssl_private_key = ssl_private_key botsglobal.logger.info(_(u'Bots web-server uses ssl (https).')) else: botsglobal.logger.info(_(u'Bots web-server uses plain http (no ssl).')) #***start the cherrypy webserver. try: botswebserver.start() except KeyboardInterrupt: botswebserver.stop()
def run(self): wsgi_app = loadapp('config:%s' % self.config['httpd_config'], relative_to=self.config['httpd_working_directory'], global_conf={ 'cassandra_host': self.config['cassandra_host'], 'cassandra_port': self.config['cassandra_port'], 'cassandra_timeout': self.config['cassandra_timeout'], 'ident': self.config['ident'] }) server = wsgiserver.CherryPyWSGIServer( (self.config['httpd_host'], int(self.config['httpd_port'])), wsgiserver.WSGIPathInfoDispatcher({'/': wsgi_app})) try: self.logger.debug( 'Starting httpd server at %s:%s' % (self.config['httpd_host'], self.config['httpd_port'])) server.start() except socket.error: self.logger.error( 'Address already in use: %s:%s' % (self.config['httpd_host'], self.config['httpd_port'])) server.stop() except KeyboardInterrupt: self.logger.error('Httpd server stopped by KeyboardInterrupt') server.stop()
def start_server(address, port, module_state): dispatcher = wsgiserver.WSGIPathInfoDispatcher({'/': app}) server = wsgiserver.CherryPyWSGIServer((address, port), dispatcher) server_thread = threading.Thread(target=server.start) server_thread.daemon = True server_thread.start() app.module_state = module_state return server
def _start_server(self): from cherrypy import wsgiserver apps = {'/': _default_app} for path, registered_app in _app_register.iteritems(): apps[path] = registered_app d = wsgiserver.WSGIPathInfoDispatcher(apps) self.server = wsgiserver.CherryPyWSGIServer((self.bind, self.port), d) self.server.start()
def quick(): d = wsgiserver.WSGIPathInfoDispatcher({'/colord': flasktemplate}) server = wsgiserver.CherryPyWSGIServer( ('0.0.0.0', 80), d, server_name=flasktemplate.appname, ) try: server.start() except KeyboardInterrupt: server.stop()
def start_server(): global server from cherrypy import wsgiserver d = wsgiserver.WSGIPathInfoDispatcher({'/': app}) server = wsgiserver.CherryPyWSGIServer( (manager.options.webui.bind, manager.options.webui.port), d) log.debug('server %s' % server) try: server.start() except KeyboardInterrupt: stop_server()
def run_on_cherrypy_for_production(): ''' run on cherrypy without auto_reload option ''' from cherrypy import wsgiserver dispatch = wsgiserver.WSGIPathInfoDispatcher({'/': app}) server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', web_conf.PORT), dispatch) try: server.start() except KeyboardInterrupt: server.stop()
def start_server(port): global server # Ready to serve logger.info("Server is starting on port {}".format(port)) cherrypy.config.update({ 'log.screen': True }) d = wsgiserver.WSGIPathInfoDispatcher({'/': api}) server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', port), d) server.start()
def run_client(args): app.external_uri = args.external_uri from kittyBot import views if args.debug: app.run(debug=args.debug, port=args.port, host='0.0.0.0') else: d = wsgiserver.WSGIPathInfoDispatcher({'/': app}) server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', args.port), d) try: server.start() except KeyboardInterrupt: server.stop()
def run_server(app): http_config = app.config['rest_api']['http'] https_config = app.config['rest_api']['https'] signal.signal(signal.SIGTERM, signal_handler) if app.config['profile']: app.wsgi_app = ProfilerMiddleware(app.wsgi_app, profile_dir=app.config['profile']) wsgi_app = wsgiserver.WSGIPathInfoDispatcher({'/': app}) cherrypy.server.unsubscribe() cherrypy.config.update({'environment': 'production'}) if not (http_config['enabled'] or https_config['enabled']): logger.critical('No HTTP/HTTPS server enabled') exit() if https_config['enabled']: try: bind_addr_https = (https_config['listen'], https_config['port']) server_https = CherryPyWSGIServer(bind_addr=bind_addr_https, wsgi_app=wsgi_app) server_https.ssl_adapter = http_helpers.ssl_adapter(https_config['certificate'], https_config['private_key'], https_config['ciphers']) ServerAdapter(cherrypy.engine, server_https).subscribe() logger.debug('HTTPS server starting on %s:%s', *bind_addr_https) except IOError as e: logger.warning("HTTPS server won't start: %s", e) else: logger.debug('HTTPS server is disabled') if http_config['enabled']: bind_addr_http = (http_config['listen'], http_config['port']) server_http = CherryPyWSGIServer(bind_addr=bind_addr_http, wsgi_app=wsgi_app) ServerAdapter(cherrypy.engine, server_http).subscribe() logger.debug('HTTP server starting on %s:%s', *bind_addr_http) else: logger.debug('HTTP server is disabled') try: cherrypy.engine.start() cherrypy.engine.block() except KeyboardInterrupt: cherrypy.engine.stop()
def _start_server(self): from cherrypy import wsgiserver apps = {'/': _default_app} for path, registered_app in _app_register.iteritems(): apps[path] = registered_app d = wsgiserver.WSGIPathInfoDispatcher(apps) self.server = wsgiserver.CherryPyWSGIServer((self.bind, self.port), d) host = self.bind if self.bind != "0.0.0.0" else socket.gethostbyname( socket.gethostname()) log.info('Web interface available at http://%s:%s' % (host, self.port)) self.server.start()
def run(self): bind_addr = (self.config['listen'], self.config['port']) wsgi_app = wsgiserver.WSGIPathInfoDispatcher({'/': app}) self.server = wsgiserver.CherryPyWSGIServer(bind_addr=bind_addr, wsgi_app=wsgi_app) self.server.ssl_adapter = http_helpers.ssl_adapter( self.config['certificate'], self.config['private_key'], self.config['ciphers']) logger.debug('WSGIServer starting... uid: %s, listen: %s:%s', os.getuid(), bind_addr[0], bind_addr[1]) for route in http_helpers.list_routes(app): logger.debug(route) try: self.server.start() except KeyboardInterrupt: self.server.stop()
def run(self): try: server_instance = GeoIPServerInstance() self.server = wsgiserver.CherryPyWSGIServer( ('127.0.0.1', int(psi_config.GEOIP_SERVICE_PORT)), wsgiserver.WSGIPathInfoDispatcher( {'/geoip': server_instance.geoip})) # Blocks until server stopped syslog.syslog( syslog.LOG_INFO, 'started GeoIP service on port %d' % (psi_config.GEOIP_SERVICE_PORT, )) self.server.start() except Exception as e: # Log other errors and abort for line in traceback.format_exc().split('\n'): syslog.syslog(syslog.LOG_ERR, line) raise
def run(): """ Run through a CherryPy Server. :return: """ app.logger.handlers = [] ch = logging.StreamHandler() ch.setLevel('DEBUG') app.logger.addHandler(ch) from cherrypy import wsgiserver d = wsgiserver.WSGIPathInfoDispatcher({'/': app}) server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 80), d) try: server.start() except KeyboardInterrupt: server.stop()
from cherrypy import wsgiserver from mad import app if __name__ == "__main__": try: hosts = { "local": { "host": "localhost", "port": 8082 }, "live": { "host": "127.0.0.1", "port": 8082 } } opt = "local" host = hosts[opt] if opt == "local": app.run(host=host["host"], port=host["port"], debug=True) else: app_list = wsgiserver.WSGIPathInfoDispatcher({"/": app}) server = wsgiserver.CherryPyWSGIServer( (host["host"], host["port"]), app_list) server.start() except KeyboardInterrupt: server.stop() print "2.2 Server stopped [ended by user]"
def main(): def try_int(s, base=10, val=None): if s is None: return None try: return int(s, base) except ValueError: return val class Config(object): debug = False ip = '0.0.0.0' port = 4735 # HRDL on phone keyboard config = 'config.py' downloads = None shows = None movies = None def __init__(self, parser): parsed_args = parser.parse_args() if parsed_args.config is not None and not os.path.isfile( parsed_args.config): warnings.warn('File not found: {}'.format(parsed_args.config)) config_path = parsed_args.config or self.config if os.path.isfile(config_path): # noinspection PyBroadException try: parsed_config = {} with open(config_path) as config_file: six.exec_( compile(config_file.read(), config_path, 'exec'), {}, parsed_config) self.debug = parsed_config.get('debug', self.debug) self.ip = parsed_config.get('ip', self.ip) self.port = parsed_config.get('port', self.port) self.db_path = parsed_config.get('db_path', self.db_path) except: ex, val, tb = sys.exc_info() warnings.warn('Error reading: {0}: {1} ({2}'.format( parsed_args.config, ex, val)) env_debug = (os.environ.get('HARDLINKER_DEBUG', None) in ['true', 'True', '1']) self.debug = parsed_args.debug or env_debug or self.debug self.ip = parsed_args.ip or os.environ.get('HARDLINKER_IP', None) or self.ip self.port = parsed_args.port or try_int( os.environ.get('HARDLINKER_PORT', None)) or self.port self.downloads = parsed_args.downloads or os.environ.get( 'HARDLINKER_DOWNLOADS', None) self.shows = parsed_args.shows or os.environ.get( 'HARDLINKER_SHOWS', None) self.movies = parsed_args.movies or os.environ.get( 'HARDLINKER_MOVIES', None) if self.downloads is None: parser.error('downloads is not specified') if self.shows is None and self.movies is None: parser.error('shows or movies has to be specified') parser = argparse.ArgumentParser(description='Hardlinker server') parser.add_argument( '--debug', action='store_true', help='Run in debug mode. Secret key is always the same.') parser.add_argument('--ip', type=str, dest='ip', help='Bind interface. Default is {0}'.format( Config.ip)) parser.add_argument('--port', type=int, dest='port', help='Port for server. Default is {0}'.format( Config.port)) parser.add_argument('--config', type=str, dest='config', default=os.environ.get('HARDLINKER_CONFIG', None), help='Path to config file (default {0})'.format( Config.config)) parser.add_argument('--downloads', type=str, dest='downloads', help='Path to Downloads folder') parser.add_argument('--shows', type=str, dest='shows', help='Path to Shows folder') parser.add_argument('--movies', type=str, dest='movies', help='Path to Movies folder') config = Config(parser) debug = config.debug if debug: secret_key = 'Secret!' token = 'hardlinker' else: secret_key = os.urandom(24) token = ''.join(random.choice(string.ascii_letters) for _ in range(8)) input_folders = [ FolderInfo.from_path(u'Downloads', six.text_type(config.downloads)) ] output_folders = [] if config.shows is not None: output_folders.append( ShowsFolderInfo.from_path(u'Shows', six.text_type(config.shows))) if config.movies is not None: output_folders.append( MoviesFolderInfo.from_path(u'Movies', six.text_type(config.movies))) linker = Linker(input_folders, output_folders, [u'mp4', u'avi', u'mkv']) guesser = Guesser(linker) app = create_app(secret_key, token, linker, guesser) d = wsgiserver.WSGIPathInfoDispatcher({'/': app}) server_start_params = (config.ip, config.port) server = wsgiserver.CherryPyWSGIServer(server_start_params, d) print(u'Server started on {0}:{1}'.format(*server_start_params)) try: server.start() except KeyboardInterrupt: server.stop()
def run(): """ Main launcher for FliKISS :param ip: Host to serve the app :param port: Port to serve tha app :param url: Url to serve the app :param debug: Debug mode :param config: Path to alternative config file """ # create args parser parser = ArgumentParser(description=__doc__) # add arguments parser.add_argument( '-i', '--ip', help='Host to serve the app', default='127.0.0.1') parser.add_argument( '-p', '--port', help='Port to serve the app', default=8000, type=int) parser.add_argument( '-u', '--url', help='Url to serve the app', default='/') parser.add_argument( '-d', '--debug', action='store_true', help='Debug mode') parser.add_argument( '-c', '--config', help='Alternate config file', default=None) # parse given args args = parser.parse_args() # config management if args.config: app = create_app(args.config) else: # default config config_path = op.expanduser('~/.flikissrc') if op.exists(config_path): app = create_app(config_path) else: app = create_app() # debug mode if args.debug: app.debug = True app.run(port=args.port) else: # create server dispatch = wsgiserver.WSGIPathInfoDispatcher({args.url: app.wsgi_app}) server = wsgiserver.CherryPyWSGIServer((args.ip, args.port), dispatch) print('App served on {0}:{1}'.format(args.ip, args.port)) server.start()
""" All custom static configurations are set here, since most are common, it makes sense to generate them just once. """ static_path = os.path.join('/', static_dir_name) path = os.path.join(PATH, static_dir_name) configuration = {static_path: { 'tools.staticdir.on': True, 'tools.staticdir.dir': path} } return cherrypy.tree.mount(Root(), '/', config=configuration) application = wsgiserver.WSGIPathInfoDispatcher( { '/': wsgi.application, settings.STATIC_URL[:-1]: make_static_config(settings.STATIC_URL[1:-1]), settings.MEDIA_URL[:-1]: make_static_config(settings.MEDIA_URL[1:-1]) }) cherrypy.config.update({'environment': 'production', 'log.error_file': 'site.log', 'log.screen': True}) server = wsgiserver.CherryPyWSGIServer(('127.0.0.1', 8001), HTTPLogger(application), server_name='python-telegram-bot.org') try: server.start() except KeyboardInterrupt: print("Terminating server...") server.stop()
def _run(self, payment_handler): app = flask.Flask(__name__) auth = HTTPBasicAuth() @dispatcher.add_method def is_ready(): try: payment_handler.checkBlockchainService() payment_handler.checkPriceInfo() except: return False return True @dispatcher.add_method def create_order(amount, currency=config.DEFAULT_CURRENCY, item_number=None, order_id=None, gen_new = config.GEN_NEW, qr_code = False): ret = payment_handler.createOrder(amount, currency, item_number, order_id, gen_new) if ret.get('error'): return ret ret.update({'qr_image': (qr.bitcoinqr(ret['receiving_address']) if qr_code else None)}) return ret @dispatcher.add_method def check_order_status(order_id=None, special_digits=None, timestamp=None, payment_address=None): return payment_handler.CheckPaymentsFor(order_id=order_id, special_digits=special_digits, payment_address=payment_address, timestamp=timestamp) @dispatcher.add_method def get_payments(bindings= (),): return payment_handler.db.getPayments(bindings) @dispatcher.add_method def poll_payments(bindings = (),): return payment_handler.pollPayments(bindings) @dispatcher.add_method def get_invalids(bindings= (),): return payment_handler.db.getInvalids(bindings) @dispatcher.add_method def get_orders(bindings= (),): return payment_handler.db.getOrders(bindings) @dispatcher.add_method def get_address(bindings= (), ): return payment_handler.db.getAddresses(bindings) @dispatcher.add_method def get_unfilled_orders(timestamp=config.ORDER_LIFE): statement = "select * from orders where filled = 0 and timestamp > %s" %(time.time() - config.ORDER_LIFE) return payment_handler.db.rquery(statement) @dispatcher.add_method def get_filled_orders(timestamp=config.ORDER_LIFE): statement = "select * from orders where filled != 0 and timestamp > %s" %(time.time() - config.ORDER_LIFE) return payment_handler.db.rquery(statement) @dispatcher.add_method def query(statement, bindings=()): return payment_handler.db.rquery(statement, bindings) @auth.get_password def get_pw(username): if username == config.RPC_USER: return config.RPC_PASSWORD return None @app.route('/', methods = ["POST",]) @app.route('/api', methods = ["POST",]) def handle_post(): # Dispatcher is a dictionary {<method_name>: callable} try: request_json = flask.request.get_data().decode('utf-8') request_data = json.loads(request_json) assert('id' in request_data and request_data['jsonrpc'] == "2.0" and request_data['method']) except: obj_error = jsonrpc.exceptions.JSONRPCInvalidRequest(data="Invalid JSON-RPC 2.0 request format") return flask.Response(obj_error.json.encode(), 200, mimetype='application/json') jsonrpc_response = jsonrpc.JSONRPCResponseManager.handle(request_json, dispatcher) response = flask.Response(jsonrpc_response.json.encode(), 200, mimetype='application/json') return response if config.AUTH_REQUIRED: auth.login_required(handle_post) d = wsgiserver.WSGIPathInfoDispatcher({'/': app.wsgi_app}) self.server = wsgiserver.CherryPyWSGIServer((config.RPC_HOST, config.RPC_PORT), d) logging.info("API Started on %s" %( config.RPC_HOST + ':' + str(config.RPC_PORT))) self.server.start()
""" static_path = os.path.join('/', static_dir_name) path = os.path.join(PATH, static_dir_name) configuration = {static_path: { 'tools.staticdir.on': True, 'tools.staticdir.dir': path} } print configuration return cherrypy.tree.mount(Root(), '/', config=configuration) if __name__ == "__main__": host = "0.0.0.0" port = 8000 application = wsgiserver.WSGIPathInfoDispatcher({ '/': django_wsgi.application, '/static': make_static_config('static')}) server = wsgiserver.CherryPyWSGIServer( (host, port), application, server_name=None, numthreads=10, timeout=5, max=100) print("WSGI-hosting Server started on %s:%s" % (host, port)) try: server.start() except KeyboardInterrupt: cherrypy.engine.exit() print("Trapped exit, shutting down...") os._exit(1)
from cherrypy import wsgiserver import server _API_BASE = os.getenv('API_BASE') # "the base URL for the game API" _API_TOKEN = os.getenv( 'API_TOKEN') # "the individual API token given to your team" server.API_BASE = _API_BASE server.ARGS.API_token = _API_TOKEN d = wsgiserver.WSGIPathInfoDispatcher({'/': server.APP}) server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8080), d) if __name__ == '__main__': try: server.start() except KeyboardInterrupt: server.stop()
from cherrypy import wsgiserver from python_webserver import app d = wsgiserver.WSGIPathInfoDispatcher({'/': app}) server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 5000), d) if __name__ == '__main__': try: server.start() except KeyboardInterrupt: server.stop()
def start(): #NOTE: bots directory should always be on PYTHONPATH - otherwise it will not start. #***command line arguments************************** usage = ''' This is "%(name)s" version %(version)s, part of Bots open source edi translator (http://bots.sourceforge.net). The %(name)s is the web server for bots; the interface (bots-monitor) can be accessed in a browser, eg 'http://localhost:8080'. Usage: %(name)s -c<directory> Options: -c<directory> directory for configuration files (default: config). ''' % { 'name': os.path.basename(sys.argv[0]), 'version': botsglobal.version } configdir = 'config' for arg in sys.argv[1:]: if arg.startswith('-c'): configdir = arg[2:] if not configdir: print 'Error: configuration directory indicated, but no directory name.' sys.exit(1) else: print usage sys.exit(0) #***end handling command line arguments************************** botsinit.generalinit( configdir) #find locating of bots, configfiles, init paths etc. process_name = 'webserver' botsglobal.logger = botsinit.initserverlogging( process_name ) #initialise file-logging for web-server. This logging only contains the logging from bots-webserver, not from cherrypy. #***init cherrypy as webserver********************************************* #global configuration for cherrypy cherrypy.config.update({ 'global': { 'log.screen': False, 'server.environment': botsglobal.ini.get('webserver', 'environment', 'production') } }) #cherrypy handling of static files conf = { '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'media', 'tools.staticdir.root': botsglobal.ini.get('directories', 'botspath') } } servestaticfiles = cherrypy.tree.mount( None, '/media', conf ) #None: no cherrypy application (as this only serves static files) #cherrypy handling of django servedjango = WSGIHandler( ) #was: servedjango = AdminMediaHandler(WSGIHandler()) but django does not need the AdminMediaHandler in this setup. is much faster. #cherrypy uses a dispatcher in order to handle the serving of static files and django. dispatcher = wsgiserver.WSGIPathInfoDispatcher({ '/': servedjango, '/media': servestaticfiles }) botswebserver = wsgiserver.CherryPyWSGIServer( bind_addr=('0.0.0.0', botsglobal.ini.getint('webserver', 'port', 8080)), wsgi_app=dispatcher, server_name=botsglobal.ini.get('webserver', 'name', 'bots-webserver')) botsglobal.logger.log(25, _(u'Bots %(process_name)s started.'), {'process_name': process_name}) botsglobal.logger.log( 25, _(u'Bots %(process_name)s configdir: "%(configdir)s".'), { 'process_name': process_name, 'configdir': botsglobal.ini.get('directories', 'config') }) botsglobal.logger.log( 25, _(u'Bots %(process_name)s serving at port: "%(port)s".'), { 'process_name': process_name, 'port': botsglobal.ini.getint('webserver', 'port', 8080) }) #handle ssl: cherrypy < 3.2 always uses pyOpenssl. cherrypy >= 3.2 uses python buildin ssl (python >= 2.6 has buildin support for ssl). ssl_certificate = botsglobal.ini.get('webserver', 'ssl_certificate', None) ssl_private_key = botsglobal.ini.get('webserver', 'ssl_private_key', None) if ssl_certificate and ssl_private_key: if cherrypy.__version__ >= '3.2.0': adapter_class = wsgiserver.get_ssl_adapter_class('builtin') botswebserver.ssl_adapter = adapter_class(ssl_certificate, ssl_private_key) else: #but: pyOpenssl should be there! botswebserver.ssl_certificate = ssl_certificate botswebserver.ssl_private_key = ssl_private_key botsglobal.logger.log(25, _(u'Bots %(process_name)s uses ssl (https).'), {'process_name': process_name}) else: botsglobal.logger.log( 25, _(u'Bots %(process_name)s uses plain http (no ssl).'), {'process_name': process_name}) #***start the cherrypy webserver.************************************************ try: botswebserver.start() except KeyboardInterrupt: botswebserver.stop()
configuration = { static_path: { 'tools.staticdir.on': True, 'tools.staticdir.dir': path } } return cherrypy.tree.mount(Root(), '/', config=configuration) # Assuming your app has media on diferent paths, like 'css', and 'images' application = wsgiserver.WSGIPathInfoDispatcher({ '/': simpleapp_wsgi_app, '/css': make_static_config('css'), '/js': make_static_config('js'), '/images': make_static_config('images'), '/fonts': make_static_config('fonts') }) server = wsgiserver.CherryPyWSGIServer( (prod.server['host'], int(prod.server['port'])), application, server_name='simpleapp') try: server.start() except KeyboardInterrupt: print "Terminating server..."
def run(self): # While loop is for recovery from 'unknown ca' issue. while True: try: server_instance = ServerInstance(self.ip_address, self.secret, self.capabilities, self.host_id) self.server = wsgiserver.CherryPyWSGIServer( (self.ip_address, int(self.port)), wsgiserver.WSGIPathInfoDispatcher({ '/handshake': server_instance.handshake, '/download': server_instance.download, '/connected': server_instance.connected, '/routes': server_instance.routes, '/failed': server_instance.failed, '/status': server_instance.status, '/speed': server_instance.speed, '/feedback': server_instance.feedback, '/check': server_instance.check, '/stats': server_instance.stats }), numthreads=self.server_threads, timeout=20) self.server.stats['Enabled'] = True # Set maximum request input sizes to avoid processing DoS inputs self.server.max_request_header_size = 100000 self.server.max_request_body_size = 100000 # Lifetime of cert/private key temp file is lifetime of server # file is closed by ServerInstance, and that auto deletes tempfile self.certificate_temp_file = tempfile.NamedTemporaryFile() self.private_key_temp_file = tempfile.NamedTemporaryFile() self.certificate_temp_file.write( '-----BEGIN CERTIFICATE-----\n' + '\n'.join(split_len(self.certificate, 64)) + '\n-----END CERTIFICATE-----\n') self.certificate_temp_file.flush() self.private_key_temp_file.write( '-----BEGIN RSA PRIVATE KEY-----\n' + '\n'.join(split_len(self.private_key, 64)) + '\n-----END RSA PRIVATE KEY-----\n') self.private_key_temp_file.flush() self.server.ssl_adapter = ssl_pyopenssl.pyOpenSSLAdapter( self.certificate_temp_file.name, self.private_key_temp_file.name, None) psi_web_patch.patch_ssl_adapter(self.server.ssl_adapter) # Blocks until server stopped syslog.syslog(syslog.LOG_INFO, 'started %s' % (self.ip_address, )) self.server.start() break except (EnvironmentError, EOFError, SystemError, ValueError, ssl.SSLError, socket.error) as e: # Log recoverable errors and try again for line in traceback.format_exc().split('\n'): syslog.syslog(syslog.LOG_ERR, line) if self.server: self.stop_server() except TypeError as e: trace = traceback.format_exc() for line in trace.split('\n'): syslog.syslog(syslog.LOG_ERR, line) # Recover on this Cherrypy internal error # See bitbucket Issue 59 if (str(e).find("'NoneType' object") == 0 and trace.find("'SSL_PROTOCOL': cipher[1]") != -1): if self.server: self.stop_server() else: raise except Exception as e: # Log other errors and abort for line in traceback.format_exc().split('\n'): syslog.syslog(syslog.LOG_ERR, line) raise
# BAD BAD BAAAAD HACK!!!! But, who cares, right?! if 'show_id.cfg' in event.src_path: with ls_lock: global ls print("Reloading config...") ls = LocalSeriesly() event_handler = UpdateConfigHandler() observer = Observer() observer.start() observer.schedule(event_handler, '.') # start wsgi server d = wsgiserver.WSGIPathInfoDispatcher({ URI_PATH: show_data, FETCH_PATH: fetch_data }) server = wsgiserver.CherryPyWSGIServer((IP, PORT), d) # signal callback def stop_server(*args, **kwargs): server.stop() observer.stop() # add signal callback signal.signal(signal.SIGINT, stop_server) # start cherrypy server server.start()
def handle(self, *args, **options): try: import cherrypy from cherrypy import wsgiserver except Exception as msg: raise ImportError( _(u'Dependency failure: cherrypy library is needed to start the as2 server' )) cherrypy.config.update({ 'global': { 'log.screen': False, 'log.error_file': os.path.join(pyas2init.gsettings['log_dir'], 'cherrypy_error.log'), 'server.environment': pyas2init.gsettings['environment'] } }) #cherrypy handling of static files conf = { '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'static', 'tools.staticdir.root': os.path.dirname(pyas2.__file__) } } servestaticfiles = cherrypy.tree.mount(None, '/static', conf) #cherrypy handling of django servedjango = WSGIHandler( ) #was: servedjango = AdminMediaHandler(WSGIHandler()) but django does not need the AdminMediaHandler in this setup. is much faster. #cherrypy uses a dispatcher in order to handle the serving of static files and django. dispatcher = wsgiserver.WSGIPathInfoDispatcher({ '/': servedjango, '/static': servestaticfiles }) pyas2server = wsgiserver.CherryPyWSGIServer( bind_addr=('0.0.0.0', pyas2init.gsettings['port']), wsgi_app=dispatcher, server_name='pyas2-webserver') pyas2init.logger.log(25, _(u'PyAS2 server running at port: "%(port)s".'), {'port': pyas2init.gsettings['port']}) #handle ssl: cherrypy < 3.2 always uses pyOpenssl. cherrypy >= 3.2 uses python buildin ssl (python >= 2.6 has buildin support for ssl). ssl_certificate = pyas2init.gsettings['ssl_certificate'] ssl_private_key = pyas2init.gsettings['ssl_private_key'] if ssl_certificate and ssl_private_key: if cherrypy.__version__ >= '3.2.0': adapter_class = wsgiserver.get_ssl_adapter_class('builtin') pyas2server.ssl_adapter = adapter_class( ssl_certificate, ssl_private_key) else: #but: pyOpenssl should be there! pyas2server.ssl_certificate = ssl_certificate pyas2server.ssl_private_key = ssl_private_key pyas2init.logger.log(25, _(u'PyAS2 server uses ssl (https).')) else: pyas2init.logger.log(25, _(u'PyAS2 server uses plain http (no ssl).')) #***start the cherrypy webserver.************************************************ try: pyas2server.start() except KeyboardInterrupt: pyas2server.stop()