Example #1
0
def run_server():
    default_ip = get_default_ip()
    
    parser = argparse.ArgumentParser(description='Serve a domsocket application.')
    parser.add_argument('--server_ip','-s', dest='server_ip', default=default_ip,
                        help='the ip address where the zmq domsocket app is listening')
    parser.add_argument('--zmq_bind_ip','-i', dest='zmq_bind_ip', default='127.0.0.1',
                        help='the ip address where the zmq domsocket app is listening')
    parser.add_argument('--server_port','-p', dest='web_port', default=8443,
                        help='the port for the web server to listen')
    parser.add_argument('--zmq_port','-z', dest='zmq_port', default=5555,
                        help='the port for the zmq backend to listen')
    parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', 
                        help='Turn on message debugging (which makes the server seem less responsive')

    args = parser.parse_args()
    app_websocket.parsed_args = args
    config_server_openssl(args.server_ip)

    WebSocketPlugin(cherrypy.engine).subscribe()
    cherrypy.tools.websocket = WebSocketTool()

    cherrypy.engine.subscribe('stop', shutdown)

    server_info = ServerInfo(args)
    backend = init_backend(args)
    backend.start()
    root_factory = RootFactory(server_info)
    root = root_factory.create_root()
    root_conf = root_factory.get_conf()

    try:
        cherrypy.quickstart(root, '/', config=root_conf)
    finally:
        logging.info('finally clause kicked out of cherrypy.quickstart')
def run_cherrypy_server(host="127.0.0.1", port=9000):
    """
    Runs a CherryPy server on Python 2.x.
    """
    import cherrypy

    from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
    from ws4py.websocket import EchoWebSocket

    cherrypy.config.update({'server.socket_host': host,
                            'server.socket_port': port,
                            'engine.autoreload_on': False,
                            'log.screen': False})
    WebSocketPlugin(cherrypy.engine).subscribe()
    cherrypy.tools.websocket = WebSocketTool()

    class Root(object):
        @cherrypy.expose
        def index(self):
            pass

    config = {
        '/': {
            'tools.websocket.on': True,
            'tools.websocket.handler_cls': EchoWebSocket
            }
        }
    logger = logging.getLogger('autobahn_testsuite')
    logger.warning("Serving CherryPy server on %s:%s" % (host, port))

    cherrypy.quickstart(Root(), '/', config)
Example #3
0
 def browser_authorize(self):
     """
     Open a browser to the authorization url and spool up a CherryPy
     server to accept the response
     """
     webbrowser.open(self.authorize_url())
     cherrypy.quickstart(self)
Example #4
0
def main():

    config = {
        "global": {
            # Server settings
            "server.socket_host": "0.0.0.0",
            "server.socket_port": 8080,
            # Encoding
            "tools.encode.on": True,
            "tools.encode.encoding": "utf-8",
            "tools.decode.on": True,
            # URL-adaption
            "tools.trailing_slash.on": True,
        },
        # "/": {
        #     #...
        # }
    }

    # Add paths for languages to http_root (examples: "/en/aaa/", "/de/aaa/")
    for lang in LANGUAGE_CODES:
        setattr(http_root, lang, http_root)

    # Create, configure and start application
    app = cherrypy.Application(http_root, config = config)
    cherrypy.quickstart(app, config = config)
Example #5
0
 def _serve_forever(self):
     LOG.debug('Starting plotter')
     try:
         cherrypy.quickstart(self, '/', {'/': {}})
     except:
         LOG.error(helper.exc_info())
         thread.interrupt_main()
Example #6
0
def server(host='127.0.0.1',port='8899',verbose=False,open_browser=True,quiet=False):

    mode = 'development' if verbose else ''
    l2s  = True if verbose else False

    config = {
        'global': {
            'server.environment': mode,
            'server.socket_host': host,
            'server.socket_port': int(port),
            'server.log_to_screen': l2s,
            'log.screen': l2s
        },
        '/': {
            'tools.staticdir.root': webapp.html_dir
        },
        '/favicon.ico': {
            'tools.staticfile.on': True,
            'tools.staticfile.filename': webapp.html_dir + '/favicon.ico'
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "static"
        }
    }

    url = "http://%s:%s%s" % (host, port, '/')
    if not quiet:
        print "Visit this url in your browser to use the app"
        print url

    if open_browser:
        browser_open = threading.Timer(1.0,browser,args=[ url ])
        browser_open.start()
    cherrypy.quickstart(webapp.Root(),config=config)
def main():
    configure_logging()
    config = {
        '/': {'tools.gzip.on': True},
        'global': {'server.socket_host': "0.0.0.0"}
    }
    cherrypy.quickstart(MyAPI(), config=config)
Example #8
0
 def run(self, args, config):
     import cherrypy
     class HelloWorld(object):
         def index(self):
             return 'Hello, world!'
         index.exposed=True
     cherrypy.quickstart(HelloWorld())
Example #9
0
def Main():
  """Configure and start the ConstrainedNetworkServer."""
  options = ParseArgs()

  try:
    traffic_control.CheckRequirements()
  except traffic_control.TrafficControlError as e:
    cherrypy.log(e.msg)
    return

  cherrypy.config.update({'server.socket_host': '::',
                          'server.socket_port': options.port})

  if options.threads:
    cherrypy.config.update({'server.thread_pool': options.threads})

  if options.socket_timeout:
    cherrypy.config.update({'server.socket_timeout': options.socket_timeout})

  # Setup port allocator here so we can call cleanup on failures/exit.
  pa = PortAllocator(options.port_range, expiry_time_secs=options.expiry_time)

  try:
    cherrypy.quickstart(ConstrainedNetworkServer(options, pa))
  finally:
    # Disable Ctrl-C handler to prevent interruption of cleanup.
    signal.signal(signal.SIGINT, lambda signal, frame: None)
    pa.Cleanup(all_ports=True)
Example #10
0
def main():
    conf = config_server()

    # Create the root application object
    root = Root()

    cherrypy.quickstart(root, "/", config=conf)
Example #11
0
def run_cherrypy_server(host="127.0.0.1", port=8008, threads=50, daemonize=False, pidfile=None, autoreload=False):
    
    if daemonize:
        if not pidfile:
            pidfile = '~/cpwsgi_%d.pid' % port
        stop_server(pidfile)

        from django.utils.daemonize import become_daemon
        become_daemon()

        fp = open(pidfile, 'w')
        fp.write("%d\n" % os.getpid())
        fp.close()
    
    cherrypy.config.update({
        'server.socket_host': host,
        'server.socket_port': int(port),
        'server.thread_pool': int(threads),
        'checker.on': False,
    })
    
    DjangoAppPlugin(cherrypy.engine).subscribe()
    if not autoreload:
        # cherrypyserver automatically reloads if any modules change
        # Switch-off that functionality here to save cpu cycles
        # http://docs.cherrypy.org/stable/appendix/faq.html
        cherrypy.engine.autoreload.unsubscribe()

    cherrypy.quickstart()
    if pidfile:
        stop_server(pidfile)
Example #12
0
    def start(self):
        """ """
        cherrypy.config.update({
            'server.socket_host': self.host,
            'server.socket_port': self.port
        })

        WebSocketPlugin(cherrypy.engine).subscribe()
        cherrypy.tools.websocket = WebSocketTool()

        cherrypy.quickstart(ChatWebApp(), '',
                            config={
                                '/': {
                                    'tools.response_headers.on': True,
                                    'tools.response_headers.headers': [
                                        ('X-Frame-options', 'deny'),
                                        ('X-XSS-Protection', '1; mode=block'),
                                        ('X-Content-Type-Options', 'nosniff')
                                    ]
                                },
                                '/ws': {
                                    'tools.websocket.on': True,
                                    'tools.websocket.handler_cls': ChatWebSocketHandler
                                },
                            })
Example #13
0
def startup(config):
	patch_compat(config)

	pmxbot.config.update(config)
	config = pmxbot.config

	pmxbot.core._load_library_extensions()

	_init_config()

	# Cherrypy configuration here
	app_conf = {
		cherrypy._cpcompat.tonative('global', encoding='ascii'): {
			'server.socket_port': config.port,
			'server.socket_host': config.host,
			#'tools.encode.on': True,
			'tools.encode.encoding': 'utf-8',
		},
		cherrypy._cpcompat.tonative('/pmxbot.png', encoding='ascii'): {
			'tools.staticfile.on': True,
			'tools.staticfile.filename': pkg_resources.resource_filename(
				'pmxbot.web', 'templates/pmxbot.png'),
		},
	}

	cherrypy.quickstart(PmxbotPages(), config.web_base, config=app_conf)
Example #14
0
def start():
    '''
    Start the server loop
    '''
    from . import app

    root, apiopts, conf = app.get_app(__opts__)

    if apiopts.get('debug', False):
        # Start the development server
        cherrypy.quickstart(root, '/', conf)
    else:
        from . import wsgi
        application = wsgi.get_application(root, apiopts, conf)

        if not 'ssl_crt' in apiopts or not 'ssl_key' in apiopts:
            logger.error("Not starting '%s'. Options 'ssl_crt' and 'ssl_key' "
                    "are required in production mode." % __name__)

            return None

        # Mount and start the WSGI app using the production CherryPy server
        verify_certs(apiopts['ssl_crt'], apiopts['ssl_key'])

        ssl_a = wsgiserver.ssl_builtin.BuiltinSSLAdapter(
                apiopts['ssl_crt'], apiopts['ssl_key'])
        wsgi_d = wsgiserver.WSGIPathInfoDispatcher({'/': application})
        server = wsgiserver.CherryPyWSGIServer(
                (apiopts.get('host', '0.0.0.0'), apiopts['port']),
                wsgi_app=wsgi_d)
        server.ssl_adapter = ssl_a

        signal.signal(signal.SIGINT, lambda *args: server.stop())
        server.start()
Example #15
0
def run_cherrypy_server(host="127.0.0.1", port=8008, threads=50, daemonize=False, pidfile=None):
    
    if daemonize:
        if not pidfile:
            pidfile = '~/cpwsgi_%d.pid' % port
        stop_server(pidfile)

        from django.utils.daemonize import become_daemon
        become_daemon()

        fp = open(pidfile, 'w')
        fp.write("%d\n" % os.getpid())
        fp.close()
    
    cherrypy.config.update({
        'server.socket_host': host,
        'server.socket_port': int(port),
        'server.thread_pool': int(threads),
        'checker.on': False,
    })

    DjangoAppPlugin(cherrypy.engine).subscribe()

    cherrypy.quickstart()
    if pidfile:
        stop_server(pidfile)
Example #16
0
def main(args):
    # Read settings used by etherpad client
    rtfn = rLite()
    
    # Start etherpad lite client
    apiKey = rtfn.api_key()
    baseUrl = rtfn.get("etherpad-url")
    print "[rlite//Debug]: Starting with api key: %s, elite hosted at: %s" % (apiKey, baseUrl)
    elite = EtherpadLiteClient(apiKey, baseUrl)
    
    # rLite's DB management hooks etherpad lite API calls
    db = DB(elite)
    
    if args.add is not None and args.key is not None:
        print "Adding competition {0} with key {1}.".format(args.add, args.key)
        db.create_competition(args.add, args.key, add_elite=False)
        sys.exit(0)
    
    # Start web interface
    current_dir = os.path.dirname(os.path.abspath(__file__))
    config = {"/static": {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': current_dir + "/static"

    }}
    cherrypy.config.update('rtfn.ini')
    # Web interface uses DB (authentication), and elite (pad lists/info)
    cherrypy.quickstart(RootController(db, rtfn, elite), "/", config=config)
Example #17
0
def wmain(argv):
  apn = None
  if len(argv) < 3:
    try:
      apn = settings.appname
      if len(argv) < 2:
        sys.stderr.write('%s bibletable [appname]\n' % (argv[0], ))
        return 1
    except:
      sys.stderr.write('%s bibletable [appname]\n\nIf appname is not provided in settings.appname, then pass it in as an arg.' % (argv[0], ))
      return 2
  else:
    apn = argv[2]
  orm.ORM.connect(dbname = 'revence', user = '******')	#
  cherrypy.server.socket_host = '0.0.0.0'
  cherrypy.quickstart(Bible(argv[1], apn), '/', {
    '/' : {
      'tools.sessions.on' : True
    },
    '/static'  : {
      'tools.staticdir.on'  : True,
      'tools.staticdir.root': os.path.abspath(os.getcwd()),
      'tools.staticdir.dir' : 'static'
    }
  })
  return 0
Example #18
0
def main(uri=schema.default_uri):
	import cherrypy as cp
	
	db = schema.connect(uri)
	providers = [
		transit_routes(db),
		coordinate_shape(db),
		coordinate_shapes(db),
		departure_traces(db),
		RouteStatisticsProvider(db),
		route_graph_edges(db),
		available_date_range(db),
		]
	
	resources = session_server.ResourceServer(providers)
	my_static = os.path.join(os.path.dirname(__file__), 'ui')
	root = session_server.StaticUnderlayServer(my_static)
	root.resources = resources

	cpconfig = {
		'server.socket_host': config.server_host,
		'server.socket_port': config.server_port,
		'tools.gzip.on': True,
		'tools.gzip.mime_types': ['text/*', 'application/json']
		}
	cp.quickstart(root, config={'global': cpconfig})
Example #19
0
    def run(self):
        #Set up the logger
        logger = logging.getLogger('wiseserver')
        logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        handler = logging.handlers.TimedRotatingFileHandler('wise_daemon.log', 'midnight', backupCount = 15)
        handler.setLevel(logging.DEBUG)
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        #Fetch the data
        try:
            credFile = open('credentials.txt', 'r')
            usr, passwd = credFile.readline().split(' ')
            credFile.close()
        except IOError:
            sys.exit(0)

        df = dataFetcher(usr, passwd[0:-1], 'extractor_data.o', logger)

        if os.path.exists('extractor_data.o'):
            df.fetchSerialized()
        else:
            df.fetchNetData()
            df.serialize()

        cherrypy.log.access_log.addHandler(handler)
        cherrypy.log.error_log.addHandler(handler)
        cherrypy.log.screen = False
        cherrypy.config.update({'server.socket_port': 8080, 'server.socket_host': '0.0.0.0', })
        conf = {'/favicon.ico':{'tools.staticfile.on': True, 'tools.staticfile.filename': os.path.join(os.getcwd(), 'favicon.ico')}}
        cherrypy.quickstart(WiseMLServer(df, logger), '/', conf)
Example #20
0
def main():
	conf = {
		'/': {
			'tools.sessions.on': True,
			'tools.staticdir.root': os.path.abspath(os.getcwd())
		},
		'/generator': {
			'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
			'tools.response_headers.on': True,
			'tools.response_headers.headers': [('Content-Type', 'text/plain')]
		},
		'/static': {
			'tools.staticdir.on': True,
			'tools.staticdir.dir': './public'
		}
	}

	# When server starts, setup the database
	cherrypy.engine.subscribe('start', setup_database)
	# When server shuts down, clean it up by removing tables
	cherrypy.engine.subscribe('stop', cleanup_database)

	webapp = StringGenerator()
	webapp.generator = StringGeneratorWebService()
	cherrypy.quickstart(webapp, '/', conf)
	return
Example #21
0
    def start(cls):
        ctx = SpellMatcherContext(metadata=metadata, session=session, mapper=mapper)
        cherrypy.config.update({
                'server.socket_host': ctx.host,
                'server.socket_port': ctx.port,
                'tools.encode.on': True, 
                'tools.encode.encoding': 'utf-8',
                'tools.decode.on': True,
                'tools.trailing_slash.on': True,
                'tools.staticdir.root': ctx.static,
                'tools.SATransaction.on': True,
                'tools.SATransaction.dburi': ctx.db_connection,
                'tools.SATransaction.echo': False,
                'tools.SATransaction.convert_unicode': True,
                'log.screen': True,
                'tools.sessions.on': True
            })

        conf = {
            '/': {
                'request.dispatch': cls.__setup_routes(ctx),
            },
            '/media': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': 'media/' + ctx.template
            }
        }

        app = cherrypy.tree.mount(None, config=conf)
        
        cherrypy.quickstart(app)
Example #22
0
def serve(path=None, port=8080):
    import cherrypy
    cherrypy.config.update({'server.socket_port': int(port),
                            'server.thread_pool': 10,
                            'environment': "production",
                            })
    cherrypy.quickstart(Profiler(path))
Example #23
0
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()
Example #24
0
    def start():

        def create_rule_if_not_exists(rule):
            out = sglib.ShellCmd('iptables-save')()
            if rule in out:
                return

            sglib.ShellCmd('iptables %s' % rule)()

        def prepare_default_rules():
            sglib.ShellCmd('iptables --policy INPUT DROP')()
            name = 'default-chain'
            try:
                sglib.ShellCmd('iptables -F %s' % name)()
            except Exception:
                sglib.ShellCmd('iptables -N %s' % name)()

            create_rule_if_not_exists('-I INPUT -p tcp --dport 9988 -j ACCEPT')
            create_rule_if_not_exists('-I INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT')


        prepare_default_rules()
        cherrypy.log.access_file = '/var/log/cs-securitygroup.log'
        cherrypy.log.error_file = '/var/log/cs-securitygroup.log'
        cherrypy.server.socket_host = '0.0.0.0'
        cherrypy.server.socket_port = 9988
        cherrypy.quickstart(SGAgent())
Example #25
0
def main():
    cherrypy.config.update({'server.socket_host': '0.0.0.0',})
    cherrypy.config.update({'server.socket_port': int(os.environ.get('PORT', '5000')),})

    ROOTDIR = os.path.dirname(os.path.abspath(__file__))
    conf = {
        '/': {
            'tools.staticdir.root': ROOTDIR,
        },
        '/js': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'js'
        },
        '/templates': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'templates'
        },
        '/favicon.ico': {
            'tools.staticfile.on': True,
            'tools.staticfile.filename': os.path.join(ROOTDIR, 'static', 'favicon.ico')
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'static'
        }
    }

    tweets = load_tweets(TWEETS_FILE)
    cherrypy.quickstart(Root(tweets), '/', config=conf)
Example #26
0
def start_service():


	#Make controller and dispatcher objects
	dictionaryController = DictionaryController()
	dispatcher = cherrypy.dispatch.RoutesDispatcher()


	#GET:
	dispatcher.connect('dict_get', '/dictionary/:key',controller=dictionaryController,
				action = 'GET',conditions=dict(method=['GET']))
	dispatcher.connect('dict_get_all','/dictionary/',controller=dictionaryController, 
				action = 'GET_ALL',conditions=dict(method=['GET']))
	#PUT
	dispatcher.connect('dict_put','/dictionary/:key',controller=dictionaryController, 
				action = 'PUT',conditions=dict(method=['PUT']))
	#POST
	dispatcher.connect('dict_post','/dictionary/',controller=dictionaryController, 
				action = 'POST',conditions=dict(method=['POST']))
	#DELETE
	dispatcher.connect('dict_del','/dictionary/:key',controller=dictionaryController, 
				action = 'DELETE',conditions=dict(method=['DELETE']))
	dispatcher.connect('dict_del_all','/dictionary/',controller=dictionaryController, 
				action = 'DELETE_ALL',conditions=dict(method=['DELETE']))

	#Configuration
	conf = {'global': {'server.socket_host': '127.0.0.1', 'server.socket_port':40041},
		'/'	: {'request.dispatch':dispatcher}}


	#Update the configuration and start the server
	cherrypy.config.update(conf)
	app = cherrypy.tree.mount(None,config=conf)
	cherrypy.quickstart(app)
Example #27
0
def main():

   find_rop_gadgets(libcfile)
   with open('exploit.mp4', 'wb') as tmp:
      tmp.write(exploit_mp4())
      cherrypy.config.update({'server.socket_host': '0.0.0.0'} )  
      cherrypy.quickstart(ExploitServer())
Example #28
0
def start_experiment(configuration_file, results_root_dir):
    task_dict, param_dict = load_config(configuration_file, results_root_dir)

    server = ExperimentServer(task_dict, param_dict, render)
    cherrypy.config.update({'server.socket_port': PORT,
                            'server.socket_host': '0.0.0.0'})
    cherrypy.quickstart(server)
Example #29
0
def main():
    #cherrypy.config.update({'error_page.404': error_page_404})
    cherrypy.config.update('webapiner.ini')
    
    core = Core(current_dir)
    core.loadConfig("")
    core.initManagers()
    rest_service = RESTService(core)

    cherrypy.tree.mount(rest_service, "/api/", config = {'/':{'request.dispatch':cherrypy.dispatch.MethodDispatcher()}})
    
    conf = {
        '/static':
        { 'tools.staticdir.on':True,
          'tools.staticdir.dir': current_dir + "/static"
        },
    }
    

    Root._cp_config = {'tools.staticdir.on' : True,
                  'tools.staticdir.dir' : os.path.join(current_dir, "static"),
                  'tools.staticdir.index' : 'index.html',
                  'tools.caching.on' :False}

    with open("webapiner.pid","w") as f:
        f.write(str(os.getpid()))
    
    cherrypy.engine.subscribe("stop", core.getManager("asset").stop)
    core.getManager("asset").start()
    #core.getManager("kb").autoload()
    cherrypy.quickstart(Root(core), config = conf)
Example #30
0
def main():
    global db

    root = Root()
    root.movie = Movies()
    root.tv = TV()
    root.about = About()
    root.media = Media()
    root.atv = ATV()
    root.log = Log()

    conf = {
        'global': {
            'server.socket_host': '0.0.0.0',
            'server.socket_port': PORT,
            'tools.staticdir.root': '/Users/dschuetz/Work/AppleTV/rPI',
        },
        '/': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
        },
        '/images': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'images',
        }
    }

    cherrypy.quickstart(root, '/', conf)
Example #31
0
        .new-date { border-bottom: 2px solid #666; }
        #flaky-rate tr :nth-child(1) { width: 70%; }

        /* make sparkline data not show up before loading */
        .inlinesparkline { color: #fff; }
        /* fix sparkline tooltips */
        .jqstooltip {
          -webkit-box-sizing: content-box;
          -moz-box-sizing: content-box;
          box-sizing: content-box;
        }
      </style>
    </head>
    <body>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sparklines/2.1.2/jquery.sparkline.min.js"></script>
      <div class="container-fluid">
      {{ body }}
      </div>
    </body>
    </html>
    """)
        return template.render(body=body)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    cherrypy.config.update({'server.socket_host': '0.0.0.0'})
    cherrypy.quickstart(TRServer())
Example #32
0
import random
import string

import cherrypy


class StringGenerator(object):
    @cherrypy.expose
    def index(self):
        return """<html>
          <head></head>
          <body>
            <form method="get" action="generate">
              <input type="text" value="8" name="length" />
              <button type="submit">Give it now!</button>
            </form>
          </body>
        </html>"""

    @cherrypy.expose
    def generate(self, length=8):
        return "".join(random.sample(string.hexdigits, int(length)))


if __name__ == "__main__":
    cherrypy.quickstart(StringGenerator())
            return 'Invalid input parameter(s)'

    @cherrypy.expose
    def SourceUsbNew(self,
                     name=None,
                     width=None,
                     height=None,
                     fps_n=None,
                     fps_d=None):
        if name and width and height and fps_n and fps_d:
            try:
                retval = dms_source_usb_new(name, int(width), int(height),
                                            int(fps_n), int(fps_d))
            except:
                retval = sys.exc_info()[0]
            return retval

        else:
            return 'Invalid input parameter(s)'


root = Root()

hostconf = os.path.join(os.path.dirname(__file__), 'host.conf')

if __name__ == '__main__':
    # CherryPy always starts with app.root when trying to map request URIs
    # to objects, so we need to mount a request handler root. A request
    # to '/' will be mapped to Root().index().
    cherrypy.quickstart(root, config=hostconf)
Example #34
0
#@-others
root = Gear()

# setup static, images and downloads directories
application_conf = {
    '/static': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': _curdir + "/static"
    },
    '/images': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': data_dir + "/images"
    },
    '/downloads': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': data_dir + "/downloads"
    }
}

# if inOpenshift ('OPENSHIFT_REPO_DIR' exists in environment variables) or not inOpenshift
if __name__ == '__main__':
    if 'OPENSHIFT_REPO_DIR' in os.environ.keys():
        # operate in OpenShift
        application = cherrypy.Application(root, config=application_conf)
    else:
        # operate in localhost
        cherrypy.quickstart(root, config=application_conf)

#@-leo
Example #35
0
import cherrypy


class EventCriteria(object):
    @cherrypy.expose
    def request(self):
        return 'hello world'


cherrypy.quickstart(EventCriteria(), '/', "/src/server.conf")
Example #36
0
#!/usr/bin/python3
import cherrypy
config = {
    'global' : {
        #'server.socket_host' : '192.168.0.109',
        'server.socket_port' : 8080
    }
}


class Servidor(object):
    @cherrypy.expose
    def index(self):
        return 'Hello World!'

    @cherrypy.expose
    def greet(self, name):
        return 'Hello {}!'.format(name)

cherrypy.quickstart(Servidor(),'/',config)
Example #37
0
            });
          </script>
        </head>
        <body>
        <form action='/echo' id='chatform' method='get'>
          <textarea id='chat' cols='35' rows='10'></textarea>
          <br />
          <label for='message'>%(username)s: </label><input type='text' id='message' />
          <input type='submit' value='Send' />
          </form>
        </body>
        </html>
        """ % {
                'username': "******" % random.randint(0, 100)
            }

        @cherrypy.expose
        def index(self):
            cherrypy.log("Handler created: %s" %
                         repr(cherrypy.request.ws_handler))

    cherrypy.quickstart(Root(),
                        '/',
                        config={
                            '/': {
                                'tools.websocket.on': True,
                                'tools.websocket.handler_cls':
                                EchoWebSocketHandler
                            }
                        })
Example #38
0
import base64


class HelloWorld:
    def index(self):
        d = self.plot()
        return ''' <form action="/">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="firstname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input type="submit" value="Submit">
</form>
 <img src="data:image/png;base64,%s" width="640" height="480" border="0" /> ''' % (
            d.decode('utf8'))

    index.exposed = True
    print(cherrypy.request.params.get('firstname'))

    def plot(self):
        image = BytesIO()
        x = numpy.linspace(0, 10)
        y = numpy.sin(x)
        pyplot.plot(x, y)
        pyplot.savefig(image, format='png')
        return base64.encodestring(image.getvalue())


if __name__ == '__main__':
    cherrypy.quickstart(HelloWorld())
Example #39
0
        if 'content-length' in cherrypy.request.headers and 'content-type' in cherrypy.request.headers and cherrypy.request.headers[
                'content-type'] == 'application/json':
            length = int(cherrypy.request.headers['content-length'])
            json_string = cherrypy.request.body.read(length).decode("utf-8")
            update = telebot.types.Update.de_json(json_string)
            bot.process_new_updates([update])
            return ''
        else:
            raise cherrypy.HTTPError(403)


@bot.message_handler(func=lambda message: True, content_types=['text'])
def echo_message(message):
    bot.reply_to(message, message.text)


bot.remove_webhook()

bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH,
                certificate=open(WEBHOOK_SSL_CERT, 'r'))

cherrypy.config.update({
    'server.socket_host': WEBHOOK_LISTEN,
    'server.socket_port': WEBHOOK_PORT,
    'server.ssl_module': 'builtin',
    'server.ssl_certificate': WEBHOOK_SSL_CERT,
    'server.ssl_private_key': WEBHOOK_SSL_PRIV
})

cherrypy.quickstart(WebhookServer(), WEBHOOK_URL_PATH, {'/': {}})
    def __init__(self):
        self.albums = Album()

    def _cp_dispatch(self, vpath):
        if len(vpath) == 1:
            cherrypy.request.params['name'] = vpath.pop()
            return self

        if len(vpath) == 3:
            cherrypy.request.params['artist'] = vpath.pop(0)  # /band name/
            vpath.pop(0)  # /albums/
            cherrypy.request.params['title'] = vpath.pop(0)  # /album title/
            return self.albums

        return vpath

    @cherrypy.expose
    def index(self, name):
        return 'About %s...' % name

    pass


class Album(object):
    @cherrypy.expose
    def index(self, artist, title):
        return 'About %s by %s...' % (title, artist)

if __name__ == '__main__':
    cherrypy.quickstart(Band())
Example #41
0
        if 'content-length' in cherrypy.request.headers and \
           'content-type' in cherrypy.request.headers and \
           cherrypy.request.headers['content-type'] == 'application/json':
            length = int(cherrypy.request.headers['content-length'])
            json_string = cherrypy.request.body.read(length).decode("utf-8")
            requests.post(BOT_2_ADDRESS, data=json_string)
            return ''
        else:
            raise cherrypy.HTTPError(403)


if __name__ == '__main__':

    bot_1.remove_webhook()
    bot_1.set_webhook(url='https://122.122.122.122/AAAA',
                      certificate=open(WEBHOOK_SSL_CERT, 'r'))

    bot_2.remove_webhook()
    bot_2.set_webhook(url='https://122.122.122.122/ZZZZ',
                      certificate=open(WEBHOOK_SSL_CERT, 'r'))

    cherrypy.config.update({
        'server.socket_host': WEBHOOK_LISTEN,
        'server.socket_port': WEBHOOK_PORT,
        'server.ssl_module': 'builtin',
        'server.ssl_certificate': WEBHOOK_SSL_CERT,
        'server.ssl_private_key': WEBHOOK_SSL_PRIV,
        'engine.autoreload.on': False
    })
    cherrypy.quickstart(WebhookServer(), '/', {'/': {}})
Example #42
0
 def run(self):
     conf = {'/': {}}
     cherrypy.quickstart(self.__root, '/', conf)
Example #43
0
    def __init__(self, queue):
        self.queue = queue

    @cherrypy.tools.json_out()
    def GET(self):
        return "okay"

    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def POST(self):
        print(cherrypy.request.json)


if __name__ == "__main__":
    conf = {
        '/': {
            'request.dispatch':
            cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on':
            True,
            'tools.response_headers.headers':
            [('Content-Type', 'application/json')]
        },
        'global': {
            'server.socket_host': '0.0.0.0'
        }
    }

    mobileye = MobileyeImageCompressor(JoinableQueue())
    cherrypy.quickstart(mobileye, '/', conf)
Example #44
0
import cherrypy
from cherrypy._cpserver import Server


class Hello(object):
    @cherrypy.expose
    def index(self):
        return 'OK'


if __name__ == '__main__':
    port = 8081
    for i in range(10):
        port += 1
        server = Server()
        server.socket_port = port
        server.subscribe()

    cherrypy.quickstart(Hello(), '/')
      True or False
    """
        with fiona.open(shp) as fc:
            point = Point(float(lon), float(lat))  # longitude, latitude
            for feature in fc:
                if shape(feature['geometry']).contains(point):
                    return True


#def capitalizeWords(s):
#  return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)

static_config = {
    '/': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': PATH,
        'tools.staticdir.index': 'index.html',
        'log.screen': True,
        #       'tools.auth_basic.on': True,
        #       'tools.auth_basic.realm':
        #         'Please use Chrome or Firefox to access this site.',
        #       'tools.auth_basic.checkpassword': validate_password
    },
}

cherrypy.config.update({
    'server.socket_host': '0.0.0.0',
    'server.socket_port': int(sys.argv[1]),
})
cherrypy.quickstart(Root(), config=static_config)
Example #46
0
"""
Main function.
"""

import os
import sys

import cherrypy

from archive import Archive


def CORS():
    """
    cors
    """
    cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"


if __name__ == '__main__':
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)

    CONF_FILE_REL = sys.argv[1] if len(sys.argv) == 2 and os.path.isfile(
        sys.argv[1]) else "archive.conf"

    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    CONF_FILE_ABS = os.path.join(BASE_DIR, CONF_FILE_REL)
    cherrypy.log.error_log.setLevel('ERROR')
    cherrypy.config.update(CONF_FILE_ABS)
    cherrypy.quickstart(Archive.get_instance(), config=CONF_FILE_ABS)
Example #47
0
import cherrypy

import device_db


class DeviceDataWebService(object):
    @cherrypy.tools.accept(media='application/json')
    @cherrypy.expose
    def index(self, brand=None, model=None, os=None, osVersion=None):
        if not brand:
            return ""
        return device_db.new_device_data(brand, model, device_db.OsType[os], osVersion)

    @cherrypy.expose(['devices'])
    # @cherrypy.tools.json_out() # not working with Enum for now
    def devices(self, brand=None, model=None, os=None, osVersion=None, page=None):
        return device_db.query(brand=brand, model=model, os=device_db.OsType[os] if os else None, osVersion=osVersion, page=page)


if __name__ == '__main__':
    cherrypy.quickstart(DeviceDataWebService())
        return json.dumps({"status": "ok"})

    @cherrypy.expose
    def beat(self, beat, ping=-1):
        if float(ping) > 0:
            self.starttime = self.starttime - float(ping) / 2
        return json.dumps({"currenttime": time.time()})

    @cherrypy.expose
    def start(self):
        """ with open("bars.json") as bars:
            sequence = json.loads(bars.read())
        bars=sequence["bars"]
        bpm = sequence["bpm"]
        self.commands=barToCommands(bars,self.locations,bpm)"""
        self.starttime = time.time()

        return json.dumps({"currenttime": time.time()})


if __name__ == '__main__':
    cherrypy.config.update({
        'server.socket_host': '0.0.0.0',
        'server.socket_port': 8080,
        'server.ssl_certificate': '/etc/nginx/ssl/nginx.crt',
        'server.ssl_private_key': '/etc/nginx/ssl/nginx.key',
        'tools.sessions.on': True,
        'tools.sessions.timeout': 10
    })
    cherrypy.quickstart(flashserver())
Example #49
0
    my_database.exposed = True

    def exit_application(self):
        mainframe.engine.exit()
        exit_contents = """
<section class="col-sm-6 mx-auto text-center text-info">
    <label>You have exited the CGPA Application</label>
</section>
        """
        return self.display.page_open(
        ), exit_contents, self.display.page_close()

    exit_application.exposed = True


#Initialization of application on custom server and port
if __name__ == '__main__':
    current_dir = os.path.dirname(os.path.abspath(__file__))
    conf = {
        "global": {
            "server.socket_host": '127.0.0.1',
            "server.socket_port": 3000,
            "server.thread_pool": 10
        },
        "/": {
            "tools.staticdir.on": True,
            "tools.staticdir.dir": current_dir
        }
    }
    mainframe.quickstart(CummulativeGradePointAverage(), "/", config=conf)
Example #50
0
    # Start rpyc server
    thread.start_new_thread(RPYC_SERVER.start, ())
    logInfo('RPYC Serving on 0.0.0.0:{}'.format(RPYC_PORT))

    # CherryPy config
    CONF = {
        'global': {
            'server.socket_host': '0.0.0.0',
            'server.socket_port': SERVER_PORT,
            'server.thread_pool': 90,
            'engine.autoreload.on': False,
            'log.screen': False,
            'tools.sessions.on': True,
            'tools.sessions.timeout': 60 * 24 * 365,
            'tools.auth_basic.on': True,
            'tools.auth_basic.realm': 'Twister Server',
            'tools.auth_basic.checkpassword': Project.check_passwd,
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': TWISTER_PATH + '/server/static',
        },
    }

    # Start !
    cherrypy.engine.signal_handler.handlers['SIGTERM'] = close
    cherrypy.quickstart(CE, '/', config=CONF)

#
Example #51
0
</script>
<a href="javascript:startPolling();">start</a> |
<a href="javascript:stopPolling();">stop</a>
<br/>
<a href="/">Okay then</a>
        """

    @cherrypy.expose
    def poll(self):
        if not self.conn:
            self.conn = pymongo.Connection(mongostring)
        while True:
            try:
                return "%s" % self.conn.data.thingoes.find({'x': True}).count()
            except AutoReconnect:
                continue
            except:
                break


if __name__ == '__main__':
    current_dir = os.path.dirname(os.path.abspath(__file__))
    print current_dir
    conf = {
        '/': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': current_dir + '/files'
        },
    }
    cherrypy.quickstart(Root(), "/", config=conf)
Example #52
0
            "redirect_uri": callback
        }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)

    def authresponse(self, var=None, **params):
        code = urllib.quote(cherrypy.request.params['code'])
        callback = cherrypy.url()
        payload = {
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "code": code,
            "grant_type": "authorization_code",
            "redirect_uri": callback
        }
        url = "https://api.amazon.com/auth/o2/token"
        r = requests.post(url, data=payload)
        resp = r.json()
        return "Success! Here is your refresh token:<br>{}".format(
            resp['refresh_token'])

    index.exposed = True
    authresponse.exposed = True


cherrypy.config.update({'server.socket_host': 'localhost'})
cherrypy.config.update({'server.socket_port': WEB_PORT})
print('Open http://localhost:3000 to login in amazon alexa service')
cherrypy.quickstart(Start())
        st = story.split('.')
        body = []
        for i in st:
            body.append(pr.get_cont(i, title))
        rep = '\n'.join(body)
        s = s.replace('{{body}}', rep)
        return s


if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd()),
            'engine.autoreload_on': False,
        },
        '/generator': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
        }
    }

    webapp = StringGenerator()
    #webapp.generator = StringGeneratorWebService()
    cherrypy.quickstart(webapp, '/', conf)
Example #54
0
 def start(self):
     self._build()
     cherrypy.quickstart(self.server)
            transform_output = io.StringIO()
            with redirect_stdout(transform_output):
                transform_json(boardstate)
            move_param = transform_output.getvalue()
            request = cherrypy.serving.request
            request.json = loads(move_param)

            move_output = io.StringIO()
            with redirect_stdout(move_output):
                result = self.move()
            output = move_output.getvalue()

        return (
            f'{html_begin}{boardstate}{html_middle}<hr>{result}<br><textarea rows="16" cols="120">{output}</textarea>{html_end}'
        )

    def log(self, message):
        # output message iwth globals
        print(f"{self.game_id} [{self.turn}] {message}")


if __name__ == "__main__":
    server = Battlesnake()
    cherrypy.config.update({"server.socket_host": "0.0.0.0"})
    cherrypy.config.update({
        "server.socket_port":
        int(os.environ.get("PORT", "8080")),
    })
    print("Starting Battlesnake Server...")
    cherrypy.quickstart(server)
Example #56
0
import cherrypy
from cherrypy import expose


class Converter:
    @expose
    def index(self):
        return "Hello World!"

    @expose
    def fahr_to_celc(self, degrees):
        temp = (float(degrees) - 32) * 5 / 9
        return "%.01f" % temp

    @expose
    def celc_to_fahr(self, degrees):
        temp = float(degrees) * 9 / 5 + 32
        return "%.01f" % temp


cherrypy.quickstart(Converter())
Example #57
0
def main():
    cherrypy.quickstart(TimeService())
Example #58
0
def start():
    cherrypy.quickstart(ScoutServer(), '/', conf)
Example #59
0
import cherrypy
import os
import searchassistant


class HelloWorld(object):

    # Method
    test = searchassistant.Test()

    # Method
    @cherrypy.expose
    def index(self):
        return "Hello world!"


conf = {
    'global': {
        'server.socket_host': '0.0.0.0',
        'server.socket_port': int(os.environ.get('PORT', 8084)),
    },
    '/': {
        'tools.staticdir.root': os.path.abspath(os.getcwd())
    },
    '/static': {
        'tools.staticdir.on': True,
        'tools.staticdir.dir': './static'
    }
}
cherrypy.quickstart(HelloWorld(), '/', config=conf)
Example #60
0
            'user': self.get_user(),
            'year': datetime.now().year,
        }
        return self.render('formProfissional.html', tparams)

    @cherrypy.expose
    def logout(self):
        self.set_user()
        raise cherrypy.HTTPRedirect("/")

    @cherrypy.expose
    def signup(self):
        pass

    @cherrypy.expose
    def shut(self):
        cherrypy.engine.exit()

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './static'
        }
    }
    cherrypy.quickstart(WebApp(), '/', conf)