当前位置: 首页>>代码示例>>Python>>正文


Python Application.listen方法代码示例

本文整理汇总了Python中tornado.web.Application.listen方法的典型用法代码示例。如果您正苦于以下问题:Python Application.listen方法的具体用法?Python Application.listen怎么用?Python Application.listen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tornado.web.Application的用法示例。


在下文中一共展示了Application.listen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def main():
    arr_threads = []

    #TODO: rebuild RequestQueue from log, and set currentJobID


    #prepare Thread to Consume RequestQueue and Produce ProcessQueue
    for i in range(nr_jobSaver):
        arr_threads.append(JobSaver(i))

    #prepare Thread to Consume ProcessQueue
    for i in range(nr_jobConsumer):
        arr_threads.append(JobConsumer(i))

    #start threads
    for t in arr_threads:
        t.start()

    #start server for incoming jobs
    app = Application([
        url(r"/", JobHandler),
        url(r"/status", StatusHandler),
        url(r"/stop", StopServerHandler),
    ])
    app.listen(8888)
    ioloop.IOLoop.current().start()
开发者ID:felix021,项目名称:pyTaskQ,代码行数:28,代码来源:pyTaskQ.py

示例2: main

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def main():
    root_dir = os.path.abspath(os.path.split(__file__)[0])
    print(root_dir)
    app = Application([(r'/gfxtablet', GfxTabletHandler),
                       #(r'/(index.js|src/.*\.js|node_modules/.*\.js)', StaticFileHandler, {}),
                       (r'/', MainHandler)],
                      debug=config.get('DEBUG', False), static_path=root_dir, static_url_prefix='/static/')

    _logger.info("app.settings:\n%s" % '\n'.join(['%s: %s' % (k, str(v))
                                                  for k, v in sorted(app.settings.items(),
                                                                     key=itemgetter(0))]))

    port = config.get('PORT', 5000)

    app.listen(port)
    _logger.info("listening on port %d" % port)
    _logger.info("press CTRL-C to terminate the server")
    _logger.info("""
           -----------
        G f x T a b l e t
    *************************
*********************************
STARTING TORNADO APP!!!!!!!!!!!!!
*********************************
    *************************
        G f x T a b l e t
           -----------
""")
    IOLoop.instance().start()
开发者ID:jzitelli,项目名称:GfxTablet.js,代码行数:31,代码来源:tornado_server.py

示例3: init_websocket_server

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def init_websocket_server():
    '''Initialize websocket server.'''

    app = Application([
        (r'/judge', JudgeHandler),
    ])
    app.listen(2501)
开发者ID:ChienYuLu,项目名称:judge,代码行数:9,代码来源:Server.py

示例4: run_auth_server

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def run_auth_server():
    client_store = ClientStore()
    client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8081/callback"])

    token_store = TokenStore()

    provider = Provider(
        access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4()
    )
    provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter()))

    try:
        app = Application(
            [
                url(provider.authorize_path, OAuth2Handler, dict(provider=provider)),
                url(provider.token_path, OAuth2Handler, dict(provider=provider)),
            ]
        )

        app.listen(8080)
        print("Starting OAuth2 server on http://localhost:8080/...")
        IOLoop.current().start()

    except KeyboardInterrupt:
        IOLoop.close()
开发者ID:rcmlee99,项目名称:python-oauth2,代码行数:27,代码来源:tornado_server.py

示例5: start

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def start(current_info):
    '''
    Start an instance of the server. 
    '''
    io_utilities.safe_make_dirs(os.path.dirname(TORNADO_LOG_FILE_PREFIX))
    tornado.options.options.log_file_prefix = TORNADO_LOG_FILE_PREFIX
    tornado.options.parse_command_line()
    
    logging.info("Starting up server on machine %s and port %s at %s." % 
                 (current_info[MACHINE], current_info[PORT_HEADER], 
                  time.strftime("%I:%M:%S")))
    
    tr = WSGIContainer(app)
    application = Application([ (r"/tornado", MainHandler),
                                (r".*", FallbackHandler, dict(fallback=tr)),
                              ])
    application.listen(PORT)
    
    # Gracefully handle server shutdown.
    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)
    signal.signal(signal.SIGQUIT, sig_handler)
    
    # Add the current info to the running info file.
    write_running_info([current_info])
    
    IOLoop.instance().start()
开发者ID:ddicara-gb,项目名称:gnubio-rest_api,代码行数:29,代码来源:server.py

示例6: run

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def run():
    parser = ArgumentParser()
    parser.add_argument("-f", "--fake", action="store_true", help="Use a fake connection for development")
    parser.add_argument("-i", "--id", default=socket.gethostname(), help="ID of this site")
    args = parser.parse_args()

    if args.fake:
        m = MissileLauncher(FakeMissileLauncherConnection())
    else:
        m = MissileLauncher(MissileLauncherConnection(0))

    config = {
        'launcher': m,
        'id': args.id
    }

    application = Application([
        (r"/position", PositionHandler, config),
        (r"/move/(-?[01])/(-?[01])", PositionHandler, config),
        (r"/move_to/([-0-9.]*)/([-0-9.]*)", MoveHandler, config),
        (r"/fire_at/([-0-9.]*)/([-0-9.]*)", FireHandler, config),
        (r"/calibrate", CalibrateHandler, config),
        (r"/", IndexHandler),
        (r"/static/(.*)", StaticFileHandler, {'path': 'static/'})
    ], debug=True)

    application.listen(7777)
    periodic = PeriodicCallback(m.timestep, 100)
    periodic.start()
    print('Site {} listening at http://{}:7777'.format(args.id, socket.gethostname()))
    IOLoop.instance().start()
开发者ID:JohannesEbke,项目名称:rapidfeedback,代码行数:33,代码来源:missilesite.py

示例7: main

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def main():
    define("host", default="127.0.0.1", help="Host IP")
    define("port", default=8080, help="Port")
    define("mongodb_url", default="127.0.0.1:27017", help="MongoDB connection URL")
    tornado.options.parse_command_line()

    client = motor.motor_tornado.MotorClient(options.mongodb_url)
    db = client['imgr']
    
    template_dir = os.getenv('OPENSHIFT_REPO_DIR', '')
    template_dir = os.path.join(template_dir, 'imgr/templates')
    static_dir = os.getenv('OPENSHIFT_DATA_DIR', os.path.dirname(__file__))
    static_dir = os.path.join(static_dir, 'static')

    settings = {
        "static_path": static_dir,
        'template_path': template_dir
    }

    application = Application([(r"/files/([^/]+)/?", MainHandler, dict(db=db)),
                                (r"/files/?", MainHandler, dict(db=db)),
                                (r'/?', HomeHandler, ), 
                                (r'/([^/]+)/?', FileHandler, )],
                                **settings)
    application.listen(options.port, options.host)

    tornado.ioloop.IOLoop.instance().start()
开发者ID:helderm,项目名称:imgr,代码行数:29,代码来源:webapp.py

示例8: run

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def run():
    ns = parse_args()

    log.init(ns.verbose, ns.quiet, logpath=ns.log)

    server_routes = [
        (r"/api/problems/([a-zA-Z_.-]+)/?", ProblemsHandler),
        (r"/api/solvers/([a-zA-Z_.-]+)/?", SolversHandler),
        (r"/api/run/?", RunSolverHandler),
        (r"/([a-zA-Z_.-]+)?/?", TemplatesHandler)
    ]

    server_settings = {
        "cookie_secret": "101010",  # todo: generate a more secure token
        "template_path": "http/templates/",
        "static_path": "http/assets",
        "static_url_prefix": "/assets/",
        # allow to recompile templates on each request, enable autoreload
        # and some other useful features on debug. See:
        # http://www.tornadoweb.org/en/stable/guide/running.html#debug-mode
        "debug": Conf['state'] == 'DEBUG'
    }

    # start the server.
    logging.info("Server Starts - %s state - %s:%s"
                 % (Conf['state'], 'localhost', Conf['server']['port']))

    application = Application(server_routes, **server_settings)
    application.listen(Conf['server']['port'])

    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        logging.warning("Keyboard Interrupt: exiting now.")
开发者ID:Hiestaa,项目名称:ml-bench,代码行数:36,代码来源:server.py

示例9: _init

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def _init(crc, settings_path):
    global backdoor_process
    backdoor_process = BackdoorProcess(crc, settings_path, loop=_loop)
    setup_logger(backdoor_process.settings)
    backdoor_process.logger = getLogger('backdoor')
    tornado_port = backdoor_process.ports['tornado']

    handlers = [
        (r'/crossdomain.xml', CrossDomainHandler),
        (r'/', BackdoorGateway),
        (r'/user/', BackdoorUserHandler),
        (r'/processes/', BackdoorActiveProcessesHandler),
        (r'/wipe/', BackdoorWipeHandler),
        (r'/map/', MapHandler),
        (r'/commands_log_(.*)\.json', CommandsLogHandler),

        (r'/static/(.+)', DevelopmentStaticHandler, {
            'path': [
                norm_path('engine', 'apps', 'backdoor', 'static'),
            ]
        }),
    ]

    tornado_settings = {
        'template_path': norm_path('engine', 'apps', 'backdoor', 'templates'),
        'xheaders': True,
        'debug': True
    }

    application = Application(handlers, **tornado_settings)
    application.listen(tornado_port, address=backdoor_process.settings['server']['backdoor']['address'])
    getLogger('process').info('Tornado listening to port {0}'.format(tornado_port))

    backdoor_process.start()
开发者ID:kollad,项目名称:turbo-ninja,代码行数:36,代码来源:server.py

示例10: __call__

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
 def __call__(self):
     sys.path.append(self._config.project_path)
     import app.routing
     from Pails.core.routes.Route import Route
     routing = Route().optimize()
     path_helper = routing[1]
     routes = []
     routes.append(('/public/(.*)', StaticFileHandler, {'path' : self._config.project_path + '/' + 'public/'}))
     for (route, variables, controller, methods, name) in routing[0]:
         params = {
             'controller': self.__get_controller(controller),
             'methods': methods,
             'param_names': variables,
             'name' : controller,
             'project_path' : self._config.project_path,
             'url_helper' : routing[1]
         }
         routes.append((route, BaseHandler, params))
     settings = {
         'cookie_secret' : 'oko'
     }
     app = Application(routes, **settings)
     app.listen(8888)
     IOLoop.instance().start()
     print 'running server'
开发者ID:far-rel,项目名称:Pails,代码行数:27,代码来源:Run.py

示例11: startThread

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
    def startThread(self):
        try:
            #static_path= os.path.join(local_path, 'static')
            handlers = [(r"/", MainHandler),
                        (r"/electrometer/*", ElectrometerSocketHandler, {"parent" : self, "data":self._jsonThread}),
                        (r"/fpga", FpgaDataHandler, {"parent" : self}),
                        (r"/(.*)",DefaultHandler),
                        ]
            
            settings = {
                'default_handler_class': DefaultHandler,
                'template_path':  "/var/www/templates",
                'static_path': "/var/www/static",
                'debug': True
            }
            
            ElectrometerSocketHandler._log = self
            handler_list = self.getHandlers()
            for handler in handler_list:
                logging.getLogger('tornado.application').addHandler(handler)
                logging.getLogger('tornado.access').addHandler(handler)
            
            application = Application(handlers, **settings)
            application.listen(self._webport)

            self.logMessage("Starting server...", self.INFO)
            
            try:
                import tornado.ioloop
                self._webthread = thread.start_new_thread(tornado.ioloop.IOLoop.current().start())
                self.logMessage("Finished...", self.INFO)
            except KeyboardInterrupt:
                self.logMessage("^C received, shutting down the web server", self.INFO)
        except Exception, e:
            self.logMessage("Failed to start WebServer due to %s"%str(e), self.ERROR)
开发者ID:mbroseta,项目名称:alin,代码行数:37,代码来源:webserver.py

示例12: run

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def run(uri=CACHE_URI, port=PORT, debug=False):
    """
    Run the server.

    uri: (optional, ./cache.db) The path to the cache database.
    port: (optional, 8080) The port to run the server on.
    debug: (optional, False) Run in debug mode.
    """
    connection = sqlite3.connect(uri, uri=True)
    connection.executescript(SCHEMA)
    connection.commit()
    connection.close()

    application = Application(
        {
            URLSpec(r'/', Index, name='index'),
            URLSpec(r'/twitter/([A-Za-z0-9_]+)', Status, name='status'),
            URLSpec(r'/twitter/([A-Za-z0-9_]+)/rss.xml', Feed, name='rss'),
        },
        db_uri=uri,
        debug=debug
    )

    application.listen(port)
    IOLoop.current().start()
开发者ID:bcj,项目名称:nolongeronline,代码行数:27,代码来源:nolongeronline.py

示例13: start

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
def start():
    from tornado.log import enable_pretty_logging
    enable_pretty_logging()
    tornado.options.parse_command_line()

    import_object('devsniff.proxy')
    import_object('devsniff.admin')

    server_root = dirname(__file__)
    proxy_settings = dict(
        debug=tornado_options.debug,
        template_path=path_join(server_root, "templates"),
        static_path=path_join(server_root, "static"),
    )
    proxy_app = TornadoWebApplication(route.get_routes(), **proxy_settings)
    proxy_bind = parse_bind_address(tornado_options.bind)

    if tornado_options.debug:
        proxy_app.listen(proxy_bind[1], proxy_bind[0])
    else:
        server = tornado.httpserver.HTTPServer(proxy_app)
        server.bind(proxy_bind[1], proxy_bind[0])
        server.start(0)

    io_loop = tornado.ioloop.IOLoop.instance()
    io_loop.add_callback(init_app)
    io_loop.start()
开发者ID:jianingy,项目名称:devsniff,代码行数:29,代码来源:cmd.py

示例14: run

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
 def run(self):
     loop = IOLoop()
     app = Application([
         (r'/', WsSocketHandler)
     ])
     app.listen(self.port)
     loop.start()
开发者ID:poppy-project,项目名称:pypot,代码行数:9,代码来源:ws.py

示例15: __init__

# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import listen [as 别名]
class HTTPServer:
  def __init__(self,address="0.0.0.0",port="8080",root="/dev/null",database={}):
    self.port = port
    self.address = address
    self.running = False
    self.root = root
    self.database = database
    
    self.application = Application([
        (r"/", IndexHandler,dict(database=database)),
        (r"/static/(.*)", StaticFileHandler, {"path": self.root})
    ])
  
  def _run(self):
    self.running = True
    try:
      self.application.listen(self.port)
      IOLoop.instance().start()
      self.running = False
    except:
      logging.error("Can't start HTTP server")
      self.running = False
    
  def start(self):
    logger.info("Starting HTTP server %s:%s"%(self.address,self.port))
    Thread(None, self._run ).start()
    
  def stop(self):
    IOLoop.instance().stop()
开发者ID:targuan,项目名称:autoinstall,代码行数:31,代码来源:httpserver.py


注:本文中的tornado.web.Application.listen方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。