Exemplo n.º 1
0
def setup_server():
    if not os.path.exists(has_space_filepath):
        file(has_space_filepath, 'wb').write('Hello, world\r\n')
        
    class Root:
        pass

    class Static:
        
        def index(self):
            return 'You want the Baron? You can have the Baron!'
        index.exposed = True
        
        def dynamic(self):
            return "This is a DYNAMIC page"
        dynamic.exposed = True
    
    
    cherrypy.config.update({'environment': 'test_suite'})
    
    root = Root()
    root.static = Static()
    
    rootconf = {
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'static',
            'tools.staticdir.root': curdir,
        },
        '/style.css': {
            'tools.staticfile.on': True,
            'tools.staticfile.filename': os.path.join(curdir, 'style.css'),
        },
        '/docroot': {
            'tools.staticdir.on': True,
            'tools.staticdir.root': curdir,
            'tools.staticdir.dir': 'static',
            'tools.staticdir.index': 'index.html',
        },
        '/error': {
            'tools.staticdir.on': True,
            'request.show_tracebacks': True,
        },
        }
    rootApp = cherrypy.Application(root)
    rootApp.merge(rootconf)
    
    test_app_conf = {
        '/test': {
            'tools.staticdir.index': 'index.html',
            'tools.staticdir.on': True,
            'tools.staticdir.root': curdir,
            'tools.staticdir.dir': 'static',
            },
        }
    testApp = cherrypy.Application(Static())
    testApp.merge(test_app_conf)
    
    vhost = cherrypy._cpwsgi.VirtualHost(rootApp, {'virt.net': testApp})
    cherrypy.tree.graft(vhost)
Exemplo n.º 2
0
def get_app():
    _set_environ_for_app_engine()
    main = cp.Application(Main())
    api = cp.Application(API(), '/api')
    api_config = {
        '/': {
            'tools.json_out.on': True,
            'tools.json_in.on': True,
            'request.dispatch': cp.dispatch.MethodDispatcher()
        }
    }
    cp.tree.mount(main, '')
    cp.tree.mount(api, config=api_config)
    return cp.tree
Exemplo n.º 3
0
def main():

    config = {
        "global": {
            # Server settings
            "server.socket_host": "0.0.0.0",
            "server.socket_port": 8080,
        },
        "/": {
            # Enable CgiServer
            "tools.cgiserver.on": True,
            # Directory with Python-CGI files
            "tools.cgiserver.dir": os.path.join(THISDIR, "pycgi"),
            # URL for directory with Python-CGI files
            "tools.cgiserver.base_url": "/",
            # Connect Python extension with Python interpreter program
            "tools.cgiserver.handlers": {
                ".py": "/usr/bin/python"
            },
        }
    }

    # Create and start application
    app = cherrypy.Application(None, config=config)
    cherrypy.quickstart(app, config=config)
Exemplo n.º 4
0
def startapp(app):
    # do not display server and version information
    # https://stackoverflow.com/a/55209796/2249798
    # https://stackoverflow.com/a/54947461/2249798
    cherrypy.__version__ = ""
    cherrypy.config.update({"response.headers.server": ""})
    cherrypy._cperror._HTTPErrorTemplate = \
        cherrypy._cperror._HTTPErrorTemplate.replace(
            "Powered by <a href=\"http://www.cherrypy.org\">"
            + "CherryPy %(version)s</a>\n",
            "%(version)s"
        )

    if config["mongodb"].getboolean('replicaset'):
        print("Connecting to MongoDB ReplicaSet: %s" %
              config["mongodb"]["url"])
        dbe = MongoReplicaSetClient(config["mongodb"]["url"],
                                    w="majority",
                                    maxPoolSize=16,
                                    socketTimeoutMS=60000,
                                    connectTimeoutMS=30000,
                                    waitQueueTimeoutMS=60000,
                                    waitQueueMultiple=64)
        atexit.register(dbe.close)
    else:
        print("Connecting to MongoDB: %s" % config["mongodb"]["url"])
        dbe = MongoClient(config["mongodb"]["url"],
                          maxPoolSize=16,
                          socketTimeoutMS=60000,
                          connectTimeoutMS=30000,
                          waitQueueTimeoutMS=60000,
                          waitQueueMultiple=64)
    dbm = dbe[config["mongodb"]["dbname"]]
    return cherrypy.Application(app(dbm), script_name=None, config=None)
def main():

    config = {
        "global": {
            # Server settings
            "server.socket_host": "0.0.0.0",
            "server.socket_port": 8080,
        },
        "/": {
            # Enable CgiServer
            "tools.cgiserver.on": True,
            # Directory with PHP files
            "tools.cgiserver.dir": THISDIR,
            # URL for directory with PHP files
            "tools.cgiserver.base_url": "/",
            # Connect PHP extension with PHP interpreter program
            "tools.cgiserver.handlers": {".php": "/usr/bin/php-cgi"},
            # DirectoryIndex
            "tools.cgiserver.directory_index": "phpinfo.php",
        }
    }

    # Create and start application
    app = cherrypy.Application(None, config = config)
    cherrypy.quickstart(app, config = config)
Exemplo n.º 6
0
    def setup_server():
        class ClassOfRoot(object):
            def __init__(self, name):
                self.name = name

            def index(self):
                return 'Welcome to the %s website!' % self.name

            index.exposed = True

        default = cherrypy.Application(None)
        domains = {}
        for year in range(1997, 2008):
            app = cherrypy.Application(ClassOfRoot('Class of %s' % year))
            domains['www.classof%s.example' % year] = app

        cherrypy.tree.graft(cherrypy._cpwsgi.VirtualHost(default, domains))
Exemplo n.º 7
0
    def __init__(self, host, port, http_interface, use_ssl, ca_cert,
                 ssl_key, ssl_cert, server_dh, daemon_thread_pool_size):
        # pylint: disable=too-many-arguments
        """
        Initialize HTTP daemon

        :param host: host address
        :param port: listening port
        :param http_interface:
        :param use_ssl:
        :param ca_cert:
        :param ssl_key:
        :param ssl_cert:
        :param daemon_thread_pool_size:
        """
        # Port = 0 means "I don't want HTTP server"
        if port == 0:
            return

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((host, port))
        if result == 0:
            msg = "Error: Sorry, the port %s/%d is not free" % (host, port)
            raise PortNotFree(msg)

        self.port = port
        self.host = host

        self.use_ssl = use_ssl

        protocol = 'http'
        if use_ssl:
            protocol = 'https'
        self.uri = '%s://%s:%s' % (protocol, self.host, self.port)
        logger.info("Opening HTTP socket at %s", self.uri)

        # This config overrides default processors so we put them back in case we need them
        config = {
            '/': {
                'request.body.processors': {'application/x-www-form-urlencoded': process_urlencoded,
                                            'multipart/form-data': process_multipart_form_data,
                                            'multipart': process_multipart,
                                            'application/zlib': zlib_processor},
                'tools.gzip.on': True,
                'tools.gzip.mime_types': ['text/*', 'application/json'],
            }
        }
        # disable console logging of cherrypy when not in DEBUG
        if getattr(logger, 'level') != logging.DEBUG:
            cherrypy.log.screen = False

        if use_ssl:
            CherryPyWSGIServer.ssl_adapter = Pyopenssl(ssl_cert, ssl_key, ca_cert, server_dh)

        self.srv = CherryPyWSGIServer((host, port),
                                      cherrypy.Application(http_interface, "/", config),
                                      numthreads=daemon_thread_pool_size, shutdown_timeout=1,
                                      request_queue_size=30)
Exemplo n.º 8
0
    def __init__(self, host, port, http_interface, use_ssl, ca_cert,
                 ssl_key, ssl_cert, daemon_thread_pool_size):
        self.port = port
        self.host = host
        self.srv = None
        # Port = 0 means "I don't want HTTP server"
        if self.port == 0:
            return

        self.use_ssl = use_ssl

        self.srv = None

        protocol = 'http'
        if use_ssl:
            protocol = 'https'
        self.uri = '%s://%s:%s' % (protocol, self.host, self.port)
        logger.info("Opening HTTP socket at %s", self.uri)

        # This config override default processors so we put them back in case we need them
        config = {
            '/': {
                'request.body.processors': {'application/x-www-form-urlencoded': process_urlencoded,
                                            'multipart/form-data': process_multipart_form_data,
                                            'multipart': process_multipart,
                                            'application/zlib': zlib_processor},
                'tools.gzip.on': True,
                'tools.gzip.mime_types': ['text/*', 'application/json']
            }
        }
        # disable console logging of cherrypy when not in DEBUG
        if getattr(logger, 'level') != logging.DEBUG:
            cherrypy.log.screen = False

        self.srv = CherryPyWSGIServer((host, port),
                                      cherrypy.Application(http_interface, "/", config),
                                      numthreads=daemon_thread_pool_size, shutdown_timeout=1)
        if SSL and pyOpenSSLAdapter and use_ssl:
            adapter = pyOpenSSLAdapter(ssl_cert, ssl_key, ca_cert)
            context = adapter.get_context()
            # SSLV2 is deprecated since 2011 by RFC 6176
            # SSLV3, TLSV1 and TLSV1.1 have POODLE weakness (harder to exploit on TLS)
            # So for now (until a new TLS version) we only have TLSv1.2 left

            # WE also remove compression because of BREACH weakness
            context.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3 |
                                SSL.OP_NO_TLSv1 | SSL.OP_NO_TLSv1_1 |
                                SSL.OP_NO_COMPRESSION)

            # All excluded algorithm beyond are known to be weak.
            context.set_cipher_list('DEFAULT:!DSS:!PSK:!SRP:!3DES:!RC4:!DES:!IDEA:!RC2:!NULL')

            adapter.context = context
            self.srv.ssl_adapter = adapter
        if use_ssl:
            self.srv.ssl_certificate = ssl_cert
            self.srv.ssl_private_key = ssl_key
Exemplo n.º 9
0
def get_app():
    """
    Gibt die Cherrypy-Application für die JSONRPC-Api zurück
    """

    app = cherrypy.Application(http_root, "/api")

    # cherrypy.config
    cherrypy_config = {

        # Produktivumgebung
        "environment": "production",
        "log.screen": False,
        "request.show_tracebacks": False,
        "request.show_mismatched_params": False,
        "tools.email_tracebacks.on": True,

        # Encoding der auszuliefernden HTML-Seiten
        "tools.encode.on": True,
        "tools.encode.encoding": "utf-8",
        "tools.decode.on": True,

        # Error-Page(s)
        "error_page.500": error_pages.error_page_500,
        "error_page.404": error_pages.error_page_404,
    }

    cherrypy.config.update(cherrypy_config)
    cherrypy.config.update(common.constants.COMMON_INIPATH)
    cherrypy.config.update(lib.constants.SECURITY_INIPATH)

    # app.config
    app_config = {
        "/": {
            # Error-Page(s)
            "error_page.500": error_pages.error_page_500,
            "error_page.404": error_pages.error_page_404,

            # URL Anpassung
            "tools.trailing_slash.on": False,
        },
    }
    app.config.update(app_config)
    app.merge(common.constants.COMMON_INIPATH)
    app.merge(lib.constants.SECURITY_INIPATH)

    # Logging per Email
    if cherrypy.config.get("tools.email_tracebacks.on"):
        # set up an SMTP handler to mail when the WARNING error occurs
        gae_smtp_handler = common.email.GaeSmtpHandler(
            subject="CherryPy Error - {APPNAME}".format(
                APPNAME=cherrypy.config["APPNAME"]))
        gae_smtp_handler.setLevel(logging.CRITICAL)
        cherrypy.log.error_log.addHandler(gae_smtp_handler)

    # Fertig
    return app
Exemplo n.º 10
0
def create_wsgi_app(path_to_library=None, prefix=''):
    'WSGI entry point'
    from calibre.library import db
    cherrypy.config.update({'environment': 'embedded'})
    db = db(path_to_library)
    parser = option_parser()
    opts, args = parser.parse_args(['calibre-server'])
    opts.url_prefix = prefix
    server = LibraryServer(db, opts, wsgi=True, show_tracebacks=True)
    return cherrypy.Application(server, script_name=None, config=server.config)
Exemplo n.º 11
0
    def mount(self):

        app = cherrypy.Application(self.ApplicationContainer(self))

        # Session middleware
        app.wsgiapp.pipeline.append(
            ("beaker_session", self.session_middleware))

        return cherrypy.tree.mount(app, self.virtual_path,
                                   self.application_settings)
Exemplo n.º 12
0
        def start(self):
                if not port_available("localhost", self.__port):
                        raise DepotStateException("A depot (or some " +
                                    "other network process) seems to be " +
                                    "running on port %d already!" % self.__port)

                # this uses the repo dir as the static content dir, which means that 
                # static content will not work, but we don't need it anyway for what
                # we are doing.
                scfg = config.SvrConfig(self.__dir, self.__dir, depot.AUTH_DEFAULT,
                    auto_create=True)
                scfg.init_dirs()
                scfg.acquire_in_flight()
                # we rebuild the catalog in a strange way here to avoid rebuilding
                # the index, which doesn't work
                scfg.acquire_catalog(rebuild=False)
                # prevent this depot from indexing
                scfg.catalog.searchdb_update_handle = DummyHandle()

                root = cherrypy.Application(sdepot.DepotHTTP(scfg, None))

                cherrypy.config.update({
                    "environment": "production",
                    "checker.on": True,
                    "log.screen": False,
                    "server.socket_port": self.__port,
                    "server.thread_pool": depot.THREADS_DEFAULT,
                    "server.socket_timeout": depot.SOCKET_TIMEOUT_DEFAULT,
                    "tools.log_headers.on": True
                })

                conf = {
                    "/": {
                        # We have to override cherrypy's default response_class so that
                        # we have access to the write() callable to stream data
                        # directly to the client.
                        "wsgi.response_class": dr.DepotResponse,
                    },
                    "/robots.txt": {
                        "tools.staticfile.on": True,
                        "tools.staticfile.filename": os.path.join(scfg.web_root,
                            "robots.txt")
                    },
                }

                cherrypy.config.update(conf)
                cherrypy.tree.mount(root, "", conf)

                engine = cherrypy.engine
                if hasattr(engine, "signal_handler"):
                    engine.signal_handler.subscribe()
                if hasattr(engine, "console_control_handler"):
                    engine.console_control_handler.subscribe()

                engine.start()
Exemplo n.º 13
0
def startapp(app):
    # do not display server and version information
    # https://stackoverflow.com/a/55209796/2249798
    # https://stackoverflow.com/a/54947461/2249798
    cherrypy.__version__ = ""
    cherrypy.config.update({"response.headers.server": ""})
    cherrypy._cperror._HTTPErrorTemplate = \
        cherrypy._cperror._HTTPErrorTemplate.replace(
            "Powered by <a href=\"http://www.cherrypy.org\">"
            + "CherryPy %(version)s</a>\n",
            "%(version)s"
        )

    return cherrypy.Application(app(), script_name=None, config=None)
Exemplo n.º 14
0
def getfactory(reactor):
    # Create a WSGI callable from our application
    app = cherrypy.Application(Node(LIBVIRT_URIS), "", APPCONFIG)

    # Twisted needs a threadpool to run this in
    threads = threadpool.ThreadPool(minthreads=1, maxthreads=1, name='virtweb')
    threads.start()
    # Shut it down, too!
    reactor.addSystemEventTrigger('after', 'shutdown', threads.stop)

    # Setup the twisted.web factory
    resource = wsgi.WSGIResource(reactor, threads, app)
    factory = server.Site(resource, 'server.log')
    return factory
Exemplo n.º 15
0
def main():

    config = {
        '/': {
            'tools.sessions.on': True
        },
        '/static': {
            'tools.staticdir.root': DIR,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'qual2db/static/'
        }
    }

    # Create, configure and start application
    app = cherrypy.Application(Root(constr=sql_creds['constr']), config=config)
    cherrypy.quickstart(app, config=config)
Exemplo n.º 16
0
def wsgi_app(service_cls, *args, **kwargs):
    """Return a WSGI application.

    service_cls - Class to launch web service. Must have the constants
                  service_cls.NS and service_cls.UTIL. *args and **kwargs are
                  passed to its constructor.
    """
    cherrypy.server.unsubscribe()
    cherrypy.config.update({'engine.autoreload.on': False})
    cherrypy.config.update({'environment': 'embedded'})
    cherrypy.engine.start()
    cherrypy.engine.signal_handler.unsubscribe()
    config = _configure(service_cls)
    try:
        return cherrypy.Application(service_cls(*args, **kwargs), None, config)
    finally:
        cherrypy.engine.stop()
Exemplo n.º 17
0
    def __init__(self, socket_port=0,
                 ssl_certificate="", ssl_private_key="",
                 *args, **kwargs):

        santiago.debug_log("Creating Listener.")

        super(HttpsListener, self).__init__(*args, **kwargs)

        cherrypy.server.socket_port = int(socket_port)
        cherrypy.server.ssl_certificate = ssl_certificate
        cherrypy.server.ssl_private_key = ssl_private_key

        dispatch = cherrypy.dispatch.RoutesDispatcher()
        dispatch.connect("index", "/", self.index)

        cherrypy.tree.mount(cherrypy.Application(self), "",
                            {"/": {"request.dispatch": dispatch}})

        santiago.debug_log("Listener Created.")
Exemplo n.º 18
0
def app_with_scout(scout_config=None):
    """
    Context manager that configures and installs the Scout plugin for CherryPy.
    """
    if scout_config is None:
        scout_config = {}

    scout_config["core_agent_launch"] = False
    scout_config.setdefault("monitor", True)
    Config.set(**scout_config)

    class Views(object):
        @cherrypy.expose
        def index(self, **params):  # Take all params so CherryPy doesn't 404
            return "Welcome home."

        @cherrypy.expose
        def hello(self):
            return "Hello World!"

        @cherrypy.expose
        def crash(self):
            raise ValueError("BØØM!")  # non-ASCII

        @cherrypy.expose
        def return_error(self):
            cherrypy.response.status = 503
            return "Something went wrong"

        # Serve this source file statically
        static_file = cherrypy.tools.staticfile.handler(__file__)

    app = cherrypy.Application(Views(), "/", config=None)

    # Setup according to https://docs.scoutapm.com/#cherrypy
    plugin = ScoutPlugin(cherrypy.engine)
    plugin.subscribe()

    try:
        yield app
    finally:
        plugin.unsubscribe()
        Config.reset_all()
Exemplo n.º 19
0
    def add_server(self, netloc, path, config):
        """Add a new CherryPy Application for a Virtual Host.
        Creates a new CherryPy WSGI Server instance if the host resolves
        to a different IP address or port.
        """

        from cherrypy._cpwsgi_server import CPWSGIServer
        from cherrypy.process.servers import ServerAdapter

        host, port = urllib.splitnport(netloc, 80)
        host = socket.gethostbyname(host)
        bind_addr = (host, port)
        if bind_addr not in self.servers:
            self.servers.append(bind_addr)
            server = CPWSGIServer()
            server.bind_addr = bind_addr
            adapter = ServerAdapter(cherrypy.engine, server, server.bind_addr)
            adapter.subscribe()
        self.domains[netloc] = cherrypy.Application(
            root=None, config={path.rstrip('/') or '/': config})
Exemplo n.º 20
0
def main():

    config = {
        '/': {
            'tools.sessions.on': True
        },
        '/static': {
            'tools.staticdir.root': DIR,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'qual2db/static/'
        }
    }
    # cherrypy.config.update({'server.socket_host': '0.0.0.0',
    #'server.socket_port': 8888,
    #})

    # Create, configure and start application
    app = cherrypy.Application(Root(constr=sqlite_creds['constr']),
                               config=config)

    cherrypy.quickstart(app, config=config)
Exemplo n.º 21
0
    def wsgi_application(self):
        import atexit
        import signal

        sys.stdout = sys.stderr

        cherrypy.config.update({"enviroment": "production"})

        atexit.register(self.stop_wsgi)
        # signal.signal(signal.SIGKILL, sigHandler)
        signal.signal(signal.SIGTERM, sigHandler)
        signal.signal(signal.SIGQUIT, sigHandler)

        self.sa_plugin.start()
        self.key_plugin.start()

        application = cherrypy.Application(MainView(),
                                           script_name='',
                                           config=self.CONFIG)

        return application
Exemplo n.º 22
0
	def setUpClass(cls):
		schema_file_path = os.path.join(os.path.dirname(gnubg.__file__), 
												'db_schema', 'db_schema.sql')

		process = get_launched_mysql_process()

		process.stdin.write('DROP DATABASE ' + cls.DB_NAME + ';\n')
		process.stdin.write('CREATE DATABASE ' + cls.DB_NAME + ';\n')
		process.stdin.write('USE ' + cls.DB_NAME + ';')
		with open(schema_file_path) as schema_file:
			while True:
				to_write = schema_file.read(1024)
				if not to_write:
					break
				process.stdin.write(to_write)

		process.stdin.close()
		process.wait()

		web_config = gc.get_web_config()
		db_parameters = json.loads(web_config['db']['conn.string'])
		db_parameters['db'] = cls.DB_NAME
		web_config['db']['conn.string'] = json.dumps(db_parameters)
		os.environ['BGTRAIN_CONNECT_PARAMETERS'] = json.dumps(db_parameters)

		app = gw.Application()
		app = cherrypy.Application(app, '', config = gc.get_config_file_path())
		app = wsgiref.validate.validator(app)
		server = wsgiref.simple_server.make_server(
										SERVER_HOST, SERVER_PORT, app)

		def serve():
			while True:
				if cls.done_serving:
					break
				server.handle_request()

		cls.server_thread = threading.Thread(target = serve)
		cls.server_thread.start()
Exemplo n.º 23
0
def main():

    cherrypy.config.update({
        # Host
        "server.socket_host": "0.0.0.0",
        "server.socket_port": 8080,
        # Encoding der auszuliefernden HTML-Seiten
        "tools.encode.on": True,
        "tools.encode.encoding": "utf-8",
        "tools.decode.on": True,
        # URL Anpassung
        "tools.trailing_slash.on": True,
        # Gzip
        "tools.gzip.on": True,
    })

    config = {
        "/": {
            "tools.staticdir.root": THISDIR,
            "tools.staticdir.on": True,
            "tools.staticdir.dir": "",

            # CgiServer Root
            "tools.cgiserver.root": THISDIR
        },
        "/cgi": {
            # CgiServer
            "tools.cgiserver.on": True,
            "tools.cgiserver.base_url": "/cgi",
            "tools.cgiserver.dir": "php_files",
            "tools.cgiserver.handlers": {
                ".php": "/usr/bin/php-cgi"
            },
        }
    }
    app = cherrypy.Application(Root(), config=config)

    cherrypy.quickstart(app)
Exemplo n.º 24
0
 def setup_server():
     import os
     curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
     
     import cherrypy
     
     def test_app(environ, start_response):
         status = ntob('200 OK')
         response_headers = [(ntob('Content-type'), ntob('text/plain'))]
         start_response(status, response_headers)
         output = ['Hello, world!\n',
                   'This is a wsgi app running within CherryPy!\n\n']
         keys = list(environ.keys())
         keys.sort()
         for k in keys:
             output.append('%s: %s\n' % (k,environ[k]))
         return [ntob(x, 'utf-8') for x in output]
     
     def test_empty_string_app(environ, start_response):
         status = ntob('200 OK')
         response_headers = [(ntob('Content-type'), ntob('text/plain'))]
         start_response(status, response_headers)
         return [ntob('Hello'), ntob(''), ntob(' '), ntob(''), ntob('world')]
     
     
     class WSGIResponse(object):
         
         def __init__(self, appresults):
             self.appresults = appresults
             self.iter = iter(appresults)
         
         def __iter__(self):
             return self
         
         def next(self):
             return self.iter.next()
         def __next__(self):
             return next(self.iter)
         
         def close(self):
             if hasattr(self.appresults, "close"):
                 self.appresults.close()
     
     
     class ReversingMiddleware(object):
         
         def __init__(self, app):
             self.app = app
         
         def __call__(self, environ, start_response):
             results = app(environ, start_response)
             class Reverser(WSGIResponse):
                 def next(this):
                     line = list(this.iter.next())
                     line.reverse()
                     return "".join(line)
                 def __next__(this):
                     line = list(next(this.iter))
                     line.reverse()
                     return bytes(line)
             return Reverser(results)
     
     class Root:
         def index(self):
             return ntob("I'm a regular CherryPy page handler!")
         index.exposed = True
     
     
     cherrypy.tree.mount(Root())
     
     cherrypy.tree.graft(test_app, '/hosted/app1')
     cherrypy.tree.graft(test_empty_string_app, '/hosted/app3')
     
     # Set script_name explicitly to None to signal CP that it should
     # be pulled from the WSGI environ each time.
     app = cherrypy.Application(Root(), script_name=None)
     cherrypy.tree.graft(ReversingMiddleware(app), '/hosted/app2')
Exemplo n.º 25
0
#@-others
################# (4) 程式啟動區
# 配合程式檔案所在目錄設定靜態目錄或靜態檔案
application_conf = {
    '/static': {
        'tools.staticdir.on': True,
        # 程式執行目錄下, 必須自行建立 static 目錄
        'tools.staticdir.dir': _curdir + "/static"
    },
    '/downloads': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': data_dir + "/downloads"
    },
    '/images': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': data_dir + "/images"
    }
}
root = Hello()
root.gear = gear.Gear()
cherrypy.server.socket_port = 8088
cherrypy.server.socket_host = '127.0.0.1'
if 'OPENSHIFT_REPO_DIR' in os.environ.keys():
    # 表示在 OpenSfhit 執行
    application = cherrypy.Application(root, config=application_conf)
else:
    # 表示在近端執行
    cherrypy.quickstart(root, config=application_conf)
#@-leo
Exemplo n.º 26
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""The WSGI interface module for notifications."""
import cherrypy
from pacifica.ingest.rest import Root, error_page_default
from pacifica.ingest.globals import CHERRYPY_CONFIG

cherrypy.config.update({'error_page.default': error_page_default})
# pylint doesn't realize that application is actually a callable
# pylint: disable=invalid-name
application = cherrypy.Application(Root(), '/', CHERRYPY_CONFIG)
# pylint: enable=invalid-name
Exemplo n.º 27
0
                raise cherrypy.HTTPError(
                    e.http_status, "This operation has been disabled by the "
                    "server administrator.")
            elif isinstance(e, AdminOpNotSupportedException):
                raise cherrypy.HTTPError(e.http_status,
                                         "This operation is not supported.")
            elif isinstance(e, IndexOpDisabledException):
                raise cherrypy.HTTPError(
                    e.http_status, "This operation has been disabled by the "
                    "server administrator.")
            else:
                # we leave this as a 500 for now. It will be
                # converted and logged by our error handler
                # before the client sees it.
                raise cherrypy.HTTPError(
                    status=http_client.INTERNAL_SERVER_ERROR,
                    message="".join(traceback.format_exc(e)))


wsgi_depot = WsgiDepot()
dispatcher = Pkg5Dispatch(wsgi_depot)

conf = {"/": {'request.dispatch': dispatcher.dispatch}}
application = cherrypy.Application(wsgi_depot, None, config=conf)
# Raise the level of the access log to make it quiet. For some reason,
# setting log.access_file = "" or None doesn't work.
application.log.access_log.setLevel(logging.WARNING)

# Vim hints
# vim:ts=8:sw=8:et:fdm=marker
Exemplo n.º 28
0
    def setup_server():

        class WSGIResponse(object):

            def __init__(self, appresults):
                self.appresults = appresults
                self.iter = iter(appresults)

            def __iter__(self):
                return self

            def next(self):
                return self.iter.next()

            def close(self):
                if hasattr(self.appresults, 'close'):
                    self.appresults.close()

        class ChangeCase(object):

            def __init__(self, app, to = None):
                self.app = app
                self.to = to

            def __call__(self, environ, start_response):
                res = self.app(environ, start_response)

                class CaseResults(WSGIResponse):

                    def next(this):
                        return getattr(this.iter.next(), self.to)()

                return CaseResults(res)

        class Replacer(object):

            def __init__(self, app, map = {}):
                self.app = app
                self.map = map

            def __call__(self, environ, start_response):
                res = self.app(environ, start_response)

                class ReplaceResults(WSGIResponse):

                    def next(this):
                        line = this.iter.next()
                        for k, v in self.map.iteritems():
                            line = line.replace(k, v)

                        return line

                return ReplaceResults(res)

        class Root(object):

            def index(self):
                return 'HellO WoRlD!'

            index.exposed = True

        root_conf = {'wsgi.pipeline': [('replace', Replacer)],
         'wsgi.replace.map': {'L': 'X',
                              'l': 'r'}}
        app = cherrypy.Application(Root())
        app.wsgiapp.pipeline.append(('changecase', ChangeCase))
        app.wsgiapp.config['changecase'] = {'to': 'upper'}
        cherrypy.tree.mount(app, config={'/': root_conf})
Exemplo n.º 29
0
        oldErr = sys.stderr
        oldOut = sys.stdout

        sys.stderr = io
        sys.stdout = io

        try:
            compiled = compile(script, "<script>", "exec")
            exec compiled
        except:
            io.write(traceback.format_exc())

        sys.stderr = oldErr
        sys.stdout = oldOut

        return io.getvalue()

    execute.exposed = True

    def index(self, *args, **kw):
        print args, kw
        return TEMPLATE.format(**self)

    index.exposed = True


wsgi_app = cherrypy.Application(ShellController())

if __name__ == "__main__":
    cherrypy.quickstart(ShellController(False))
Exemplo n.º 30
0
    index.exposed = True


def get_cp_config():
    config = {
        '/': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': STATIC,
            'tools.sessions.on': True
        },
        '/api': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher()
        }
    }
    return config


def runserver(config):
    cherrypy.tree.mount(Root(), '/', config)
    cherrypy.server.socket_host = "0.0.0.0"
    cherrypy.server.socket_port = 8000
    cherrypy.engine.start()
    cherrypy.engine.block()


if __name__ == "__main__":
    runserver(get_cp_config())
else:
    cherrypy.config.update({'environment': 'embedded'})
    application = cherrypy.Application(Root(), script_name=None, config=get_cp_config())