• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python ioloop.add_callback函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tornado.ioloop.add_callback函数的典型用法代码示例。如果您正苦于以下问题:Python add_callback函数的具体用法?Python add_callback怎么用?Python add_callback使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: stop

 def stop(self):
     """
     Stop tornado web server
     """
     ioloop = tornado.ioloop.IOLoop.instance()
     ioloop.add_callback(ioloop.stop)
     logger.debug("Exiting tornado...")
开发者ID:thor27,项目名称:window-manager,代码行数:7,代码来源:robot.py


示例2: fetch

 def fetch(self, callback):
     if len(self.logs) == 0:
         self.callback = callback
     else:
         logs, self.logs = self.logs, []
         for log in logs:
             ioloop.add_callback(callback, log)
开发者ID:gtagency,项目名称:ascendency,代码行数:7,代码来源:match_server.py


示例3: start_server

def start_server(args):
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret'
    app.jinja_env.globals['static'] = static

    blueprint.url_prefix = args.url_prefix
    app.register_blueprint(blueprint)

    # app.run(port=args.port, debug=args.debug)

    wsgi_app = tornado.wsgi.WSGIContainer(app)
    condajs_ws = sockjs.tornado.SockJSRouter(views.CondaJsWebSocketRouter, '/condajs_ws')
    routes = condajs_ws.urls
    routes.append((r".*", tornado.web.FallbackHandler, dict(fallback=wsgi_app)))
    application = tornado.web.Application(routes, debug=args.debug)

    try:
        application.listen(args.port)
    except OSError as e:
        print("There was an error starting the server:")
        print(e)
        return

    ioloop = tornado.ioloop.IOLoop.instance()
    if not args.debug:
        callback = lambda: webbrowser.open_new_tab('http://localhost:%s' % args.port)
        ioloop.add_callback(callback)
    ioloop.start()
开发者ID:conda,项目名称:conda-ui,代码行数:28,代码来源:__init__.py


示例4: main

def main():
    options, args = get_args()
    
    ioloop = tornado.ioloop.IOLoop.instance()
    
    series = get_series_class(options)(options, ioloop)
    
    application = Application(options, series, [
        ('/', IndexHandler),
        ('/update', UpdateHandler),
    ], static_path=STATIC_PATH)
    
    try:
        ip = get_ip_address('eth0')
    except IOError:
        ip = '127.0.0.1'

    tornado.httpserver.HTTPServer(application).listen(options.port, ip)
    
    url = 'http://%s:%s/' % (ip, options.port)
    
    def announce():
        print >>sys.stderr, "wplot running at: " + url
    
    if options.browse:
        ioloop.add_callback(lambda: webbrowser.open_new_tab(url))
    
    ioloop.add_callback(announce)
    
    try:
        ioloop.start()
    except (KeyboardInterrupt, IOError) as e:
        pass
    finally:
        application._stop = True
开发者ID:libscott,项目名称:wplot,代码行数:35,代码来源:wplot.py


示例5: enumerate_device

    def enumerate_device(this_node, node_id, response):
        global UAVCAN_NODE_INFO, UAVCAN_NODE_CONFIG
        log.debug("enumerate_device({}, {!r})".format(node_id, response))

        # Save the node info request and clear out the config
        UAVCAN_NODE_INFO[node_id] = response
        UAVCAN_NODE_CONFIG[node_id] = {}

        # Send the node info message to all connected sockets
        send_all(response.type.get_normalized_definition(), node_id, response)

        # Schedule a parameter fetch if the node is in operating mode
        if not response.status.mode:
            ioloop.add_callback(enumerate_node_params, this_node, node_id)

        # Check the supplied directory for updated firmware
        if not firmware_dir:
            log.debug("enumerate_device(): no firmware path specified")
            return

        # Search for firmware suitable for this device
        device_name = response.name.decode()
        available_files = firmware_files_for_device(
            firmware_dir, device_name, response.hardware_version.major,
            response.hardware_version.minor)

        log.debug(("enumerate_device(): found {:d} firmware file(s) " +
                   "for device '{!s}'").format(
                   len(available_files), device_name))
        for f in available_files:
            log.debug(("enumerate_device():        {!s} " +
                       "(modified {:%Y-%m-%dT%H:%M:%S})").format(
                       f[-1], datetime.datetime.fromtimestamp(f[-2])))

        # If there are files available, check the CRC of the latest version
        # against the CRC of the firmware on the node.
        if available_files:
            firmware_path = available_files[0][-1]
            with FirmwareImage(firmware_path, "rb") as f:
                if f.app_descriptor.image_crc != \
                        response.software_version.image_crc:
                    # Version mismatch, send a BeginFirmwareUpdate with the
                    # appropriate path.
                    request = uavcan.protocol.file.BeginFirmwareUpdate(
                        mode="request")
                    request.source_node_id = this_node.node_id
                    request.image_file_remote_path.path.encode(
                        os.path.basename(firmware_path))
                    (response, response_transfer), _ = yield tornado.gen.Task(
                        this_node.send_request, request, node_id)

                    if response and response.error != response.ERROR_OK:
                        msg = ("[MASTER] #{0:03d} rejected "
                               "uavcan.protocol.file.BeginFirmwareUpdate " +
                               "with error {1:d}: {2!s}").format(
                               node_id, response.error,
                               response.optional_error_message.decode())
                        log.error(msg)
                else:
                    log.debug("enumerate_device(): device up to date")
开发者ID:JarryChou,项目名称:vectorcontrol,代码行数:60,代码来源:ui.py


示例6: on_open

    def on_open(self, info):
        # type: (ConnectionInfo) -> None
        log_data = dict(extra='[transport=%s]' % (self.session.transport_name,))
        record_request_start_data(log_data)

        ioloop = tornado.ioloop.IOLoop.instance()

        self.authenticated = False
        self.session.user_profile = None
        self.close_info = None # type: CloseErrorInfo
        self.did_close = False

        try:
            self.browser_session_id = info.get_cookie(settings.SESSION_COOKIE_NAME).value
            self.csrf_token = info.get_cookie(settings.CSRF_COOKIE_NAME).value
        except AttributeError:
            # The request didn't contain the necessary cookie values.  We can't
            # close immediately because sockjs-tornado doesn't expect a close
            # inside on_open(), so do it on the next tick.
            self.close_info = CloseErrorInfo(403, "Initial cookie lacked required values")
            ioloop.add_callback(self.close)
            return

        def auth_timeout():
            # type: () -> None
            self.close_info = CloseErrorInfo(408, "Timeout while waiting for authentication")
            self.close()

        self.timeout_handle = ioloop.add_timeout(time.time() + 10, auth_timeout)
        write_log_line(log_data, path='/socket/open', method='SOCKET',
                       remote_ip=info.ip, email='unknown', client_name='?')
开发者ID:aakash-cr7,项目名称:zulip,代码行数:31,代码来源:socket.py


示例7: stop_server

def stop_server(server):
    server.stop()
    logger.info("Add stop callback.")
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.add_callback(ioloop.stop)
    logger.info("Maybe server stopping...")
    os.system("taskkill /im python.exe")
开发者ID:iandmyhand,项目名称:KOSPIRestAPI,代码行数:7,代码来源:server.py


示例8: open

 def open(self):
     ioloop = tornado.ioloop.IOLoop.instance()
     ioloop.call_later(self._KEEPALIVE_PING_TIMEOUT, self._send_ping)
     ioloop.add_callback(lambda: log.info('Client connected: {0}'.format(self)))
     self._get_id()
     self._CLIENTS[self.id] = self
     self._log_client_list()
开发者ID:ei-grad,项目名称:wsrpc,代码行数:7,代码来源:handler.py


示例9: init_timers

 def init_timers(self):
     ioloop = tornado.ioloop.IOLoop.instance()
     
     # The mongo status monitor. We set up one call immediately, and then
     # try again every three seconds.
     ioloop.add_callback(self.monitor_mongo_status)
     res = tornado.ioloop.PeriodicCallback(self.monitor_mongo_status, 3000)
     res.start()
开发者ID:Oreolek,项目名称:tworld,代码行数:8,代码来源:mongomgr.py


示例10: on_close

    def on_close(self):
            ioloop = tornado.ioloop.IOLoop.instance()
            if self._CLIENTS.has_key(self.id):
                self._CLIENTS.pop(self.id)
            for name, obj in iteritems(self.__handlers):
                ioloop.add_callback(obj._onclose)

            log.info('Client "{0}" disconnected'.format(self.id))
开发者ID:ei-grad,项目名称:wsrpc,代码行数:8,代码来源:handler.py


示例11: close

    def close(self):
        super(WebSocketBase, self).close()
        ioloop = tornado.ioloop.IOLoop.instance()

        for future in self.store.values():
            ioloop.add_callback(partial(future.set_exception, ConnectionClosed))

        ioloop.add_callback(lambda: self.on_close() if self.ws_connection else None)
开发者ID:ei-grad,项目名称:wsrpc,代码行数:8,代码来源:handler.py


示例12: read_callback

  def read_callback(self, frame):
    ts = frame.timestamp
    ioloop.add_callback(lambda:self.publish(
      'can.%03x' % frame.id, ts, frame.tojson()))

    if self.obd2:
      ioloop.add_callback(lambda:
        self.obd2.read(ts, frame.tojson()))
开发者ID:Acidburn0zzz,项目名称:carhack,代码行数:8,代码来源:canusb.py


示例13: gpio_loop

def gpio_loop():
    ioloop = tornado.ioloop.IOLoop.current()
    value = True

    while True:
        time.sleep(1.0)
        value = not value
        ioloop.add_callback(partial(WebSocketHandler.dispatch, value))
开发者ID:deets,项目名称:brombeerquark,代码行数:8,代码来源:server.py


示例14: queue_response

 def queue_response(self, response):
     ioloop = tornado.ioloop.IOLoop.instance()
     def send_response(*args):
         self._send_response(response)
     try:
         # calling write_message or the socket is not thread safe
         ioloop.add_callback(send_response)
     except:
         logging.error("Error adding callback", exc_info=True)
开发者ID:Goutte,项目名称:OpenBazaar,代码行数:9,代码来源:ws.py


示例15: on_close

    def on_close(self):
        '''
        Called when client closes this connection. Cleanup
        is done here.
        '''

        if self.id in self.funcserver.websocks:
            self.funcserver.websocks[self.id] = None
            ioloop = tornado.ioloop.IOLoop.instance()
            ioloop.add_callback(lambda: self.funcserver.websocks.pop(self.id, None))
开发者ID:lijinc,项目名称:funcserver,代码行数:10,代码来源:funcserver.py


示例16: schedule_match

 def schedule_match(self, match, worker):
     def send_schedule():
         self.send({'$schedule':{
             'match_id': match.match_id,
             'game': match.game,
             'players': match.players,
             'config': match.config
             }})
     ioloop.add_callback(send_schedule)
     self.matches[match.match_id] = match
开发者ID:gtagency,项目名称:ascendency,代码行数:10,代码来源:scheduler.py


示例17: main

def main():
    ioloop = tornado.ioloop.IOLoop.current()
    tornado.log.enable_pretty_logging()
    tornado.log.app_log.setLevel(logging.DEBUG)
    app = tornado.web.Application(
        [(r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "./static"}), (r"/api/puzzle", PuzzleHandler)]
    )
    app.listen(8888)
    ioloop.add_callback(in_app_worker)
    ioloop.add_callback(in_app_worker)
    ioloop.start()
开发者ID:chenfengyuan,项目名称:squares-solver,代码行数:11,代码来源:main.py


示例18: cbMethod

 def cbMethod( *cargs, **ckwargs ):
   cb = ckwargs.pop( 'callback' )
   method = cargs[0]
   disetConf = cargs[1]
   cargs = cargs[2]
   RESTHandler.__disetConfig.load( disetConf )
   ioloop = tornado.ioloop.IOLoop.instance()
   try:
     result = method( *cargs, **ckwargs )
     ioloop.add_callback( functools.partial( cb, result ) )
   except Exception, excp:
     exc_info = sys.exc_info()
     ioloop.add_callback( lambda : genTask.runner.handle_exception( *exc_info ) )
开发者ID:acasajus,项目名称:RESTDIRAC,代码行数:13,代码来源:RESTHandler.py


示例19: main

def main(config_file=None):
    parse_configs(config_files=config_file)

    if options.app is None:
        log.exception('no frontik application present (`app` option is not specified)')
        sys.exit(1)

    log.info('starting application %s', options.app)

    try:
        module = importlib.import_module(options.app)
    except Exception as e:
        log.exception('failed to import application module "%s": %s', options.app, e)
        sys.exit(1)

    if options.app_class is not None and not hasattr(module, options.app_class):
        log.exception('application class "%s" not found', options.app_class)
        sys.exit(1)

    application = getattr(module, options.app_class) if options.app_class is not None else FrontikApplication

    try:
        app = application(app_root=os.path.dirname(module.__file__), **options.as_dict())
        ioloop = tornado.ioloop.IOLoop.current()

        def _async_init_cb():
            try:
                init_futures = app.default_init_futures + list(app.init_async())

                if init_futures:
                    def await_init(future):
                        if future.exception() is not None:
                            log.error('failed to initialize application, init_async returned: %s', future.exception())
                            sys.exit(1)

                        run_server(app)

                    ioloop.add_future(gen.multi(init_futures), await_init)
                else:
                    run_server(app)

            except Exception:
                log.exception('failed to initialize application')
                sys.exit(1)

        ioloop.add_callback(_async_init_cb)
        ioloop.start()
    except BaseException:
        log.exception('frontik application exited with exception')
        sys.exit(1)
开发者ID:hhru,项目名称:frontik,代码行数:50,代码来源:server.py


示例20: sighup_handler

    def sighup_handler (server, ioloop, signum, frame):
        def stop_ioloop (ioloop):
            logging.info ("Stopping IOloop")
            ioloop.stop ()
            logging.info ("Done.")

        def stop_server (server, ioloop):
            logging.info ("Stopping HTTP server")
            server.stop ()
            ioloop.add_timeout (time.time () + 5.0, partial (stop_ioloop, ioloop))
            logging.info ("Waiting for pending requests")

        logging.info ("Graceful exit due to SIGHUP")
        ioloop.add_callback (partial (stop_server, server, ioloop))
开发者ID:cwells,项目名称:trailerpark,代码行数:14,代码来源:tp.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python ioloop.add_timeout函数代码示例发布时间:2022-05-27
下一篇:
Python httputil.HTTPHeaders类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap