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)
python类IOLoop()的实例源码
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 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 _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 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 __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 _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 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 __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:`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 _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)
autoreload.py 文件源码
项目:My-Web-Server-Framework-With-Python2.7
作者: syjsu
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
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 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()
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()