我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用tornado.ioloop.IOLoop()。
def __init__(self, *args, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. MotorClient takes the same constructor arguments as :class:`~pymongo.mongo_client.MongoClient`, as well as: :Parameters: - `io_loop` (optional): Special :class:`tornado.ioloop.IOLoop` instance to use instead of default """ if 'io_loop' in kwargs: io_loop = kwargs.pop('io_loop') else: io_loop = ioloop.IOLoop.current() event_class = functools.partial(util.MotorGreenletEvent, io_loop) kwargs['_event_class'] = event_class super(MotorClient, self).__init__(io_loop, *args, **kwargs)
def __init__(self, *args, **kwargs): """Create a new connection to a MongoDB replica set. MotorReplicaSetClient takes the same constructor arguments as :class:`~pymongo.mongo_replica_set_client.MongoReplicaSetClient`, as well as: :Parameters: - `io_loop` (optional): Special :class:`tornado.ioloop.IOLoop` instance to use instead of default """ if 'io_loop' in kwargs: io_loop = kwargs.pop('io_loop') else: io_loop = ioloop.IOLoop.current() kwargs['_monitor_class'] = functools.partial( MotorReplicaSetMonitor, io_loop) super(MotorReplicaSetClient, self).__init__(io_loop, *args, **kwargs)
def start(io_loop=None, check_time=500): """Begins watching source files for changes. .. versionchanged:: 4.1 The ``io_loop`` argument is deprecated. """ io_loop = io_loop or ioloop.IOLoop.current() if io_loop in _io_loops: return _io_loops[io_loop] = True if len(_io_loops) > 1: gen_log.warning("tornado.autoreload started more than once in the same process") if _has_execv: add_reload_hook(functools.partial(io_loop.close, all_fds=True)) modify_times = {} callback = functools.partial(_reload_on_update, modify_times) scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop) scheduler.start()
def _run(self): self._loop = IOLoop() self._server = FakeAnacondaServer(io_loop=self._loop, fail_these=self._fail_these, expected_basename=self._expected_basename) self._url = self._server.url def notify_started(): self._started.acquire() self._started.notify() self._started.release() self._loop.add_callback(notify_started) self._loop.start() # done self._server.unlisten()
def _testReadWrite(self): """ In this test the writer writes an 'x' to its fd. The reader reads it, check the value and ends the test. """ self.shouldWrite = True def checkReadInput(fd): self.assertEquals(fd.read(), 'x') self._reactor.stop() def writeOnce(fd): if self.shouldWrite: self.shouldWrite = False fd.write('x') self._reader = Reader(self._p1, checkReadInput) self._writer = Writer(self._p2, writeOnce) self._reactor.addWriter(self._writer) # Test that adding the reader twice adds it only once to # IOLoop. self._reactor.addReader(self._reader) self._reactor.addReader(self._reader)
def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('--serial-port', type=str, required=True) parser.add_argument('--ws-port', type=int, required=True) parser.add_argument('--verbose', action='store_true', default=False) args = parser.parse_args() loop = IOLoop() SerialToWs.serial_port = args.serial_port SerialToWs.verbose = args.verbose SerialToWs.ioloop = loop app = Application([ (r'/', SerialToWs) ]) app.listen(args.ws_port) loop.start()
def connect(host, port): loop = IOLoop() Publisher.verbose = False Publisher.ioloop = loop app = Application([ (r'/', Publisher) ]) app.listen(port) url = 'ws://{}:{}'.format(host, port) if Publisher.verbose: print('Fake robot serving on {}'.format(url)) t = Thread(target=loop.start) t.daemon = True t.start()
def __init__(self, io_loop, *args, **kwargs): check_deprecated_kwargs(kwargs) kwargs['_pool_class'] = functools.partial(MotorPool, io_loop) kwargs['_connect'] = False delegate = self.__delegate_class__(*args, **kwargs) super(MotorClientBase, self).__init__(delegate) if io_loop: if not isinstance(io_loop, ioloop.IOLoop): raise TypeError( "io_loop must be instance of IOLoop, not %r" % io_loop) self.io_loop = io_loop else: self.io_loop = ioloop.IOLoop.current()
def open(self): """Connect to the server. Takes an optional callback, or returns a Future that resolves to ``self`` when opened. This is convenient for checking at program startup time whether you can connect. .. doctest:: >>> client = MotorClient() >>> # run_sync() returns the open client. >>> IOLoop.current().run_sync(client.open) MotorClient(MongoClient('localhost', 27017)) ``open`` raises a :exc:`~pymongo.errors.ConnectionFailure` if it cannot connect, but note that auth failures aren't revealed until you attempt an operation on the open client. :Parameters: - `callback`: Optional function taking parameters (self, error) .. versionchanged:: 0.2 :class:`MotorClient` now opens itself on demand, calling ``open`` explicitly is now optional. """ yield self._ensure_connected() raise gen.Return(self)
def open(self): """Connect to the server. Takes an optional callback, or returns a Future that resolves to ``self`` when opened. This is convenient for checking at program startup time whether you can connect. .. doctest:: >>> client = MotorClient() >>> # run_sync() returns the open client. >>> IOLoop.current().run_sync(client.open) MotorClient(MongoClient('localhost', 27017)) ``open`` raises a :exc:`~pymongo.errors.ConnectionFailure` if it cannot connect, but note that auth failures aren't revealed until you attempt an operation on the open client. :Parameters: - `callback`: Optional function taking parameters (self, error) .. versionchanged:: 0.2 :class:`MotorReplicaSetClient` now opens itself on demand, calling ``open`` explicitly is now optional. """ yield self._ensure_connected(True) primary = self._get_member() if not primary: raise pymongo.errors.AutoReconnect('no primary is available') raise gen.Return(self)
def wait(): """Wait for a watched file to change, then restart the process. Intended to be used at the end of scripts like unit test runners, to run the tests again after any source file changes (but see also the command-line interface in `main`) """ io_loop = ioloop.IOLoop() start(io_loop) io_loop.start()
def _get_primary_pool(self): primary_member = self._get_member() return primary_member.pool if primary_member else None # PyMongo uses a background thread to regularly inspect the replica set and # monitor it for changes. In Motor, use a periodic callback on the IOLoop to # monitor the set.
def __init__(self, scheduler, name, user=getpass.getuser(), master=os.getenv('MESOS_MASTER', 'zk://localhost:2181'), failover_timeout=100, capabilities=None, principal=None, secret=None, implicit_acknowledgements=True, handlers={}, loop=None): self.loop = loop or IOLoop() self.master = master self.leading_master_seq = None self.leading_master_info = None self.scheduler = scheduler self.framework = { 'user': user, 'name': name, 'capabilities': capabilities or [], 'failover_timeout': failover_timeout, 'hostname': socket.gethostname() } self.implicit_acknowledgements = implicit_acknowledgements defaults = {Event.SUBSCRIBED: self.on_subscribed, Event.OFFERS: self.on_offers, Event.RESCIND: self.on_rescind, Event.UPDATE: self.on_update, Event.MESSAGE: self.on_message, Event.RESCIND_INVERSE_OFFER: self.on_rescind_inverse, Event.FAILURE: self.on_failure, Event.ERROR: self.on_error, Event.HEARTBEAT: self.on_heartbeat, Event.OUTBOUND_SUCCESS: self.on_outbound_success, Event.OUTBOUND_ERROR: self.on_outbound_error} self.handlers = merge(defaults, handlers) self.subscription = Subscription(self.framework, self.master, '/api/v1/scheduler', self.handlers, principal=principal, secret=secret, timeout=failover_timeout, loop=self.loop)
def shutdown(self, block=False): """Prohibit further produce requests and attempt to flush all events currently in the main and retry queues. After this attempt, all remaining events are made available to an event handler but will otherwise be dropped. The producer thread and IOLoop are also shut down. If block=True, this blocks until the producer thread is dead and the shutdown event has been handled.""" logger.info('Client shutting down') self.in_shutdown = True self.io_loop.add_callback(self.producer.start_shutdown) if block: self.producer_thread.join() logger.info('Client completed shutdown') else: logger.info('Client shutting down asynchronously, will not block')
def test_ui_server_empty(): def do_test(dirname): io_loop = IOLoop() io_loop.make_current() events = [] def event_handler(event): events.append(event) project = Project(dirname) local_state_file = LocalStateFile.load_for_directory(dirname) context = ConfigurePrepareContext(dict(), local_state_file, 'default', UserConfigOverrides(), []) server = UIServer(project, _no_op_prepare(context), event_handler, io_loop) get_response = http_get(io_loop, server.url) print(repr(get_response)) post_response = http_post(io_loop, server.url, body="") print(repr(post_response)) server.unlisten() assert len(events) == 1 assert isinstance(events[0], UIServerDoneEvent) with_directory_contents(dict(), do_test)
def start(io_loop=None, check_time=500): """Restarts the process automatically when a module is modified. We run on the I/O loop, and restarting is a destructive operation, so will terminate any pending requests. """ io_loop = io_loop or ioloop.IOLoop.instance() add_reload_hook(functools.partial(_close_all_fds, io_loop)) modify_times = {} callback = functools.partial(_reload_on_update, modify_times) scheduler = ioloop.PeriodicCallback(callback, check_time, io_loop=io_loop) scheduler.start()