本文整理汇总了Python中twisted.internet.reactor方法的典型用法代码示例。如果您正苦于以下问题:Python internet.reactor方法的具体用法?Python internet.reactor怎么用?Python internet.reactor使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet
的用法示例。
在下文中一共展示了internet.reactor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: request
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def request(self, callback, method, url, **kwargs):
if 'data' in kwargs and not isinstance(kwargs['data'], bytes):
# python2/3 compatibility
data = kwargs.pop('data')
kwargs['data'] = data.encode(encoding='utf-8') \
if hasattr(data, 'encode') else b(data)
try:
response = yield self.client.request(method, url, **kwargs)
parsed = yield self._get_resp(response)
returnValue(callback(self.response(*parsed)))
except ConnectError as e:
raise ConsulException(
'{}: {}'.format(e.__class__.__name__, e.message))
except ResponseNeverReceived:
# this exception is raised if the connection to the server is lost
# when yielding a response, this could be due to network issues or
# server restarts
raise ConsulException(
'Server connection lost: {} {}'.format(method.upper(), url))
except RequestTransmissionFailed:
# this exception is expected if the reactor is stopped mid request
raise ConsulException(
'Request incomplete: {} {}'.format(method.upper(), url))
示例2: acquireTriggerCheckLock
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def acquireTriggerCheckLock(self, trigger_id, timeout):
"""
acquireTriggerCheckLock(self, trigger_id, timeout)
Try to acquire lock for trigger check until timeout
:param trigger_id: trigger identity
:type trigger_id: string
:param timeout: timeout in seconds
:type timeout: float
"""
acquired = yield self.setTriggerCheckLock(trigger_id)
count = 0
while acquired is None and count < timeout:
count += 1
yield task.deferLater(reactor, 0.5, lambda: None)
acquired = yield self.setTriggerCheckLock(trigger_id)
if acquired is None:
raise Exception("Can not acquire trigger lock in {0} seconds".format(timeout))
示例3: _start_onion_service
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def _start_onion_service(self, factory):
def progress(percent, tag, message):
bar = int(percent / 10)
log.debug('[%s%s] %s' % ('#' * bar, '.' * (10 - bar), message))
def setup_complete(port):
port = txtorcon.IHiddenService(port)
self.uri = "http://%s" % (port.getHost().onion_uri)
log.info('I have set up a hidden service, advertised at: %s'
% self.uri)
log.info('locally listening on %s' % port.local_address.getHost())
def setup_failed(args):
log.error('onion service setup FAILED: %r' % args)
endpoint = endpoints.serverFromString(reactor, 'onion:80')
txtorcon.IProgressProvider(endpoint).add_progress_listener(progress)
d = endpoint.listen(factory)
d.addCallback(setup_complete)
d.addErrback(setup_failed)
return d
示例4: _get_brokerclient
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def _get_brokerclient(self, node_id):
"""
Get a broker client.
:param int node_id: Broker node ID
:raises KeyError: for an unknown node ID
:returns: :class:`_KafkaBrokerClient`
"""
if self._closing:
raise ClientError("Cannot get broker client for node_id={}: {} has been closed".format(node_id, self))
if node_id not in self.clients:
broker_metadata = self._brokers[node_id]
log.debug("%r: creating client for %s", self, broker_metadata)
self.clients[node_id] = _KafkaBrokerClient(
self.reactor, self._endpoint_factory,
broker_metadata, self.clientId, self._retry_policy,
)
return self.clients[node_id]
示例5: retry_while_broker_errors
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def retry_while_broker_errors(self, f, *a, **kw):
"""
Call a function, retrying on retriable broker errors.
If calling the function fails with one of these exception types it is
called again after a short delay:
* `afkak.common.RetriableBrokerResponseError` (or a subclass thereof)
* `afkak.common.PartitionUnavailableError`
The net effect is to keep trying until topic auto-creation completes.
:param f: callable, which may return a `Deferred`
:param a: arbitrary positional arguments
:param kw: arbitrary keyword arguments
"""
while True:
try:
returnValue((yield f(*a, **kw)))
break
except (RetriableBrokerResponseError, PartitionUnavailableError):
yield async_delay(0.1, clock=self.reactor)
示例6: __init__
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def __init__(self, logPath=None, timeout=_REQUEST_TIMEOUT,
logFormatter=None, reactor=None):
"""
@param logFormatter: An object to format requests into log lines for
the access log.
@type logFormatter: L{IAccessLogFormatter} provider
@param reactor: A L{IReactorTime} provider used to compute logging
timestamps.
"""
if not reactor:
from twisted.internet import reactor
self._reactor = reactor
if logPath is not None:
logPath = os.path.abspath(logPath)
self.logPath = logPath
self.timeOut = timeout
if logFormatter is None:
logFormatter = combinedLogFormatter
self._logFormatter = logFormatter
# For storing the cached log datetime and the callback to update it
self._logDateTime = None
self._logDateTimeCall = None
示例7: process
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def process(self):
parsed = urllib_parse.urlparse(self.uri)
protocol = parsed[0]
host = parsed[1].decode('ascii')
port = self.ports[protocol]
if ':' in host:
host, port = host.split(':')
port = int(port)
rest = urllib_parse.urlunparse((b'', b'') + parsed[2:])
if not rest:
rest = rest + b'/'
class_ = self.protocols[protocol]
headers = self.getAllHeaders().copy()
if b'host' not in headers:
headers[b'host'] = host.encode('ascii')
self.content.seek(0, 0)
s = self.content.read()
clientFactory = class_(self.method, rest, self.clientproto, headers,
s, self)
self.reactor.connectTCP(host, port, clientFactory)
示例8: __init__
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def __init__(self, host, port, path, reactor=reactor):
"""
@param host: the host of the web server to proxy.
@type host: C{str}
@param port: the port of the web server to proxy.
@type port: C{port}
@param path: the base path to fetch data from. Note that you shouldn't
put any trailing slashes in it, it will be added automatically in
request. For example, if you put B{/foo}, a request on B{/bar} will
be proxied to B{/foo/bar}. Any required encoding of special
characters (such as " " or "/") should have been done already.
@type path: C{str}
"""
Resource.__init__(self)
self.host = host
self.port = port
self.path = path
self.reactor = reactor
示例9: render
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def render(self, request):
"""
Render a request by forwarding it to the proxied server.
"""
# RFC 2616 tells us that we can omit the port if it's the default port,
# but we have to provide it otherwise
if self.port == 80:
host = self.host
else:
host = self.host + u":" + str(self.port)
request.requestHeaders.setRawHeaders(b"host", [host.encode('ascii')])
request.content.seek(0, 0)
qs = urllib_parse.urlparse(request.uri)[4]
if qs:
rest = self.path + b'?' + qs
else:
rest = self.path
clientFactory = self.proxyClientFactoryClass(
request.method, rest, request.clientproto,
request.getAllHeaders(), request.content.read(), request)
self.reactor.connectTCP(self.host, self.port, clientFactory)
return NOT_DONE_YET
示例10: _handleRead
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def _handleRead(self, rc, data, evt):
"""
Returns False if we should stop reading for now
"""
if self.disconnected:
return False
# graceful disconnection
if (not (rc or data)) or rc in (errno.WSAEDISCON, ERROR_HANDLE_EOF):
self.reactor.removeActiveHandle(self)
self.readConnectionLost(failure.Failure(main.CONNECTION_DONE))
return False
# XXX: not handling WSAEWOULDBLOCK
# ("too many outstanding overlapped I/O requests")
elif rc:
self.connectionLost(failure.Failure(
error.ConnectionLost("read error -- %s (%s)" %
(errno.errorcode.get(rc, 'unknown'), rc))))
return False
else:
assert self._readSize == 0
assert self._readNextBuffer == 0
self._readSize = data
return self._dispatchData()
示例11: connectionLost
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def connectionLost(self, reason):
"""
The connection was lost.
This is called when the connection on a selectable object has been
lost. It will be called whether the connection was closed explicitly,
an exception occurred in an event handler, or the other end of the
connection closed it first.
Clean up state here, but make sure to call back up to FileDescriptor.
"""
self.disconnected = True
self.connected = False
if self.producer is not None:
self.producer.stopProducing()
self.producer = None
self.stopReading()
self.stopWriting()
self.reactor.removeActiveHandle(self)
示例12: patchInstallReactor
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def patchInstallReactor(self):
"""
Patch C{_options.installReactor} so we can capture usage and prevent
actual installs.
"""
self.installedReactors = {}
def installReactor(name):
if name != "fusion":
raise NoSuchReactor()
reactor = MemoryReactor()
self.installedReactors[name] = reactor
return reactor
self.patch(_options, "installReactor", installReactor)
示例13: service
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def service(description, factory, reactor=None):
"""
Return the service corresponding to a description.
@param description: The description of the listening port, in the syntax
described by L{twisted.internet.endpoints.serverFromString}.
@type description: C{str}
@param factory: The protocol factory which will build protocols for
connections to this service.
@type factory: L{twisted.internet.interfaces.IProtocolFactory}
@rtype: C{twisted.application.service.IService}
@return: the service corresponding to a description of a reliable stream
server.
@see: L{twisted.internet.endpoints.serverFromString}
"""
if reactor is None:
from twisted.internet import reactor
svc = StreamServerEndpointService(
endpoints.serverFromString(reactor, description), factory)
svc._raiseSynchronously = True
return svc
示例14: listen
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def listen(description, factory):
"""
Listen on a port corresponding to a description.
@param description: The description of the connecting port, in the syntax
described by L{twisted.internet.endpoints.serverFromString}.
@type description: L{str}
@param factory: The protocol factory which will build protocols on
connection.
@type factory: L{twisted.internet.interfaces.IProtocolFactory}
@rtype: L{twisted.internet.interfaces.IListeningPort}
@return: the port corresponding to a description of a reliable virtual
circuit server.
@see: L{twisted.internet.endpoints.serverFromString}
"""
from twisted.internet import reactor
name, args, kw = endpoints._parseServer(description, factory)
return getattr(reactor, 'listen' + name)(*args, **kw)
示例15: __init__
# 需要导入模块: from twisted import internet [as 别名]
# 或者: from twisted.internet import reactor [as 别名]
def __init__(self, protocol, process=None, reactor=None):
"""
@type protocol: L{ProcessAliasProtocol}
@param protocol: The protocol associated with the child process.
@type process: L{bytes} or L{None}
@param process: The process name.
@type reactor: L{None} or L{IReactorTime
<twisted.internet.interfaces.IReactorTime>} provider
@param reactor: A reactor which will be used to schedule timeouts.
"""
self.processName = process
self.protocol = protocol
self.completion = defer.Deferred()
self.protocol.onEnd = self.completion
self.completion.addBoth(self._processEnded)
if reactor is not None:
self.reactor = reactor