How to use the cherrypy.engine function in CherryPy

To help you get started, we’ve selected a few CherryPy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github relder251 / LazyLibrarianRefresh / lazylibrarian / webStart.py View on Github external
}

    if options['http_pass'] != "":
        conf['/'].update({
            'tools.auth_basic.on': True,
            'tools.auth_basic.realm': 'LazyLibrarian',
            'tools.auth_basic.checkpassword':  cherrypy.lib.auth_basic.checkpassword_dict(
                {options['http_user']:options['http_pass']})
        })


    # Prevent time-outs
    cherrypy.engine.timeout_monitor.unsubscribe()
    cherrypy.tree.mount(WebInterface(), options['http_root'], config = conf)

    cherrypy.engine.autoreload.subscribe()

    try:
        cherrypy.process.servers.check_port(options['http_host'], options['http_port'])
        cherrypy.server.start()
    except IOError:
        print 'Failed to start on port: %i. Is something else running?' % (options['http_port'])
        sys.exit(0)

    cherrypy.server.wait()
github BenjV / autosub-bootstrapbill / cherrypy / _cpmodpy.py View on Github external
for function in options['cherrypy.setup'].split():
            atoms = function.split('::', 1)
            if len(atoms) == 1:
                mod = __import__(atoms[0], globals(), locals())
            else:
                modname, fname = atoms
                mod = __import__(modname, globals(), locals(), [fname])
                func = getattr(mod, fname)
                func()

    cherrypy.config.update({'log.screen': False,
                            'tools.ignore_headers.on': True,
                            'tools.ignore_headers.headers': ['Range'],
                            })

    engine = cherrypy.engine
    if hasattr(engine, 'signal_handler'):
        engine.signal_handler.unsubscribe()
    if hasattr(engine, 'console_control_handler'):
        engine.console_control_handler.unsubscribe()
    engine.autoreload.unsubscribe()
    cherrypy.server.unsubscribe()

    def _log(msg, level):
        newlevel = apache.APLOG_ERR
        if logging.DEBUG >= level:
            newlevel = apache.APLOG_DEBUG
        elif logging.INFO >= level:
            newlevel = apache.APLOG_INFO
        elif logging.WARNING >= level:
            newlevel = apache.APLOG_WARNING
        # On Windows, req.server is required or the msg will vanish. See
github kevinlondon / django-py2app-demo / demosite.py View on Github external
cherrypy.config.update({
            'server.socket_host': host,
            'server.socket_port': port,
            'log.screen': log,
            'engine.autoreload_on': reload,
        })
        self.cfg_assets(settings.MEDIA_URL, settings.MEDIA_ROOT)
        self.cfg_assets(settings.STATIC_URL, settings.STATIC_ROOT)
        self.cfg_favicon(settings.STATIC_ROOT)
        app = WSGIHandler()
        app = TransLogger(app, logger_name='cherrypy.access',
                          setup_console_handler=False)
        if self.domains:
            app = cherrypy.wsgi.VirtualHost(app, self.domains)
        cherrypy.tree.graft(app)
        cherrypy.engine.start()
        cherrypy.engine.block()
github cherrypy / cherrypy / py2 / cherrypy / _cpserver.py View on Github external
def __init__(self):
        self.bus = cherrypy.engine
        self.httpserver = None
        self.interrupt = None
        self.running = False
github google / gsa-admin-toolkit / connectormanager.py View on Github external
self.debug_flag = debug_flag
    cherrypy.server.socket_host = '0.0.0.0'
    self.connectorref = connectorref
    if use_ssl == True:
      cherrypy.config.update({'global': {
          'server.ssl_certificate': 'ssl.crt',
          'server.ssl_private_key': 'ssl.key', }})
    if debug_flag == True:
      cherrypy.config.update({'global': {'log.screen': True}})
    else:
      cherrypy.config.update({'global': {'log.screen': False}})
    if port is None:
      port = 38080
    cherrypy.config.update({'global': {'server.socket_port': port}})
    cherrypy.tree.mount(self, script_name='/')
    cherrypy.engine.start()
    self.loadpropfile()
    for c in connector_list:
      c.startConnector()
    self.savepropfile()
github sandialabs / slycat / packages / slycat / web / server / engine.py View on Github external
if directory_type not in list(manager.directories.keys()):
    cherrypy.log.error("slycat.web.server.engine.py start", "No directory plugin for type: %s" % directory_type)
    raise Exception("No directory plugin for type: %s" % directory_type)
  directory_args = configuration["slycat-web-server"]["directory"].get("args", [])
  directory_kwargs = configuration["slycat-web-server"]["directory"].get("kwargs", {})
  manager.directories[directory_type]["init"](*directory_args, **directory_kwargs)
  configuration["slycat-web-server"]["directory"] = manager.directories[directory_type]["user"]

  # Expand remote host aliases.
  configuration["slycat-web-server"]["remote-hosts"] = {hostname: remote for remote in configuration["slycat-web-server"]["remote-hosts"] for hostname in remote.get("hostnames", [])}

  # wsgi: this just saves this dict in the slycat obj, no cherrypy stuff here
  slycat.web.server.config = configuration

  # Start all of our cleanup workers.
  cherrypy.engine.subscribe("start", slycat.web.server.cleanup.start, priority=80)

  # sets custom 4XX pages
  cherrypy.config.update({ 'error_page.404': os.path.join(root_path, "templates/slycat-404.html") })
  cherrypy.config.update({ 'error_page.401': os.path.join(root_path, "templates/slycat-401.html") })

  # Start the web server.
  cherrypy.quickstart(None, "", configuration)
  # wsgi: for actual wsgi - don't call quickstart just rtn config below
github kovidgoyal / calibre / src / calibre / library / server / main.py View on Github external
def main(args=sys.argv):
    from calibre.db.legacy import LibraryDatabase
    parser = option_parser()
    opts, args = parser.parse_args(args)
    if opts.daemonize and not iswindows:
        daemonize()
    if opts.pidfile is not None:
        from cherrypy.process.plugins import PIDFile
        PIDFile(cherrypy.engine, opts.pidfile).subscribe()
    cherrypy.log.screen = True
    from calibre.utils.config import prefs
    if opts.with_library is None:
        opts.with_library = prefs['library_path']
    if not opts.with_library:
        print('No saved library path. Use the --with-library option'
                ' to specify the path to the library you want to use.')
        return 1
    db = LibraryDatabase(os.path.expanduser(opts.with_library))
    server = LibraryServer(db, opts, show_tracebacks=opts.develop)
    server.start()
    return 0
github stephank / libvirtweb / virtweb.py View on Github external
def deftemplate(name, mainMethodName='content'):
   """Compile a Cheetah template and add the compiled class to the globals.

   The template should be located in 'templates/name.tmpl'. Other templates
   compiled before will be made available in the template's globals.
   The template will also have the convenience functions $h and $n in
   it's globals."""

   global templates
   path = os.path.join(basepath, TEMPLATE_DIR, '%s.tmpl' % name)
   cherrypy.engine.autoreload.files.add(path)
   klass = Cheetah.Template.Template.compile(
         file=path, mainMethodName=mainMethodName, useCache=False,
         moduleName=name, className=name, moduleGlobals=templates)
   templates[name] = klass
   def tmpl(**kwargs):
      searchList = {'h': htmlescape, 'n': prettynumber}
      searchList.update(kwargs)
      inst = klass(searchList=searchList)
      cherrypy.response.headers['Content-Type'] = inst.content_type
      return inst.respond()
   globals()[name] = tmpl
github sabnzbd / sabnzbd / cherrypy / _cpconfig.py View on Github external
def merge(base, other):
    """Merge one app config (from a dict, file, or filename) into another.

    If the given config is a filename, it will be appended to
    the list of files to monitor for "autoreload" changes.
    """
    if isinstance(other, text_or_bytes):
        cherrypy.engine.autoreload.files.add(other)

    # Load other into base
    for section, value_map in reprconf.as_dict(other).items():
        if not isinstance(value_map, dict):
            raise ValueError(
                'Application config must include section headers, but the '
                "config you tried to merge doesn't have any sections. "
                'Wrap your config in another dict with paths as section '
                "headers, for example: {'/': config}.")
        base.setdefault(section, {}).update(value_map)
github danwent / Perspectives-Server / notary_http.py View on Github external
'log.error_file' : None,
			 'log.screen' : True } )

static_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), notary.STATIC_DIR)
notary_config = { '/': {'tools.staticfile.root' : static_root,
						'tools.staticdir.root' : static_root }}

app = cherrypy.tree.mount(notary, '/', config=notary_config)
app.merge("notary.cherrypy.config")

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