本文整理汇总了Python中twisted.internet.defer.Deferred.addCallback方法的典型用法代码示例。如果您正苦于以下问题:Python Deferred.addCallback方法的具体用法?Python Deferred.addCallback怎么用?Python Deferred.addCallback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.defer.Deferred
的用法示例。
在下文中一共展示了Deferred.addCallback方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_collection
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def create_collection(self, label, alias=''):
"""Create a new collection with the specified properties."""
d = Deferred()
def createcollection_handler(collection, prompt):
"""A collection was created, or a prompt should be shown first."""
if prompt != "/":
self.do_prompt(prompt).chainDeferred(d)
else:
d.callback(collection)
def error_fallback(error):
"""Fall back to using the old property name."""
properties = {CLXN_LABEL_PROPERTY_OLD: dbus.String(
label,
variant_level=1)}
self.service.CreateCollection(
properties,
reply_handler=createcollection_handler,
error_handler=d.errback)
properties = {CLXN_LABEL_PROPERTY: dbus.String(label,
variant_level=1)}
try:
self.service.CreateCollection(
properties, alias,
reply_handler=createcollection_handler,
error_handler=error_fallback)
except TypeError:
error_fallback(None)
d.addCallback(lambda p: Collection(self, p))
return d
示例2: becomeGridHost
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def becomeGridHost(self, *args):
if self.clientObject.getLocalUser().gridHost:
for uuid in self.clientObject.users:
if self.clientObject.users[uuid].gridHostActive:
#TODO: Allow moderators to take gridhost from others.
showModalDialog(
self.window,
Gtk.MessageType.ERROR,
'The grid is already being hosted.'
)
return
#TODO: Show error dialogs on failures
self.setStatus('Loading OpenSim distribution...')
distribution = Distribution(self.clientObject.projectRoot, self.clientObject.externalhost, parent=self.window)
d = Deferred()
d.addCallback(self.startRobust)
distribution.load(d)
#TODO: Don't hardcode this
else:
showModalDialog(
self.window,
Gtk.MessageType.ERROR,
'You do not have permission to become the grid host.'
)
示例3: _call
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def _call(self, msg, cb, *args):
""" Internally used method which should be used to call the service.
@param msg: Request message which should be sent.
@param cb: Callback which should be called to process
response. The response will be the first
argument and additional arguments passed to the
_call method will be passed to the callback.
@param *args: Additional arguments which will be passed to the
callback.
"""
if not self._status:
raise InterfaceDisabledError('A disabled interface should not be '
'called.')
if not callable(cb):
raise TypeError('Callback has to be callable.')
uid = uuid4().hex
deferred = Deferred()
deferred.addCallback(cb, *args)
self._responses[uid] = deferred
self._conn.sendMessage(self._iTag, self._clsName, msg, uid)
示例4: do_host_count
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def do_host_count(self, request, params = {}):
"""
Because process_host_count above is meant to handle its
own finalization, do_host_count always returns NOT_DONE_YET. Its
much simpler to make a tiny hack then hack process_host count to straddle
to different scenarios ( return string and process itself )
"""
#if this a polling request and it's not the first one
if 'ts' in params and params['ts'] != 0:
#if the caller is up to date or from the future
if params['ts'] > self.myStore.lastChange:
#hold the connection open
d = Deferred()
def deferred_host_count(self, request):
request.write(self.process_host_count)
request.finish()
#and notify them when something changes
d.addCallback(self.deferred_host_count, request)
self.myStore.onChange.observe(d)
return NOT_DONE_YET
#If no TS or TS is out of date, process NOW
return self.process_host_count(request)
示例5: test_http
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def test_http(self):
"""
When connecting to a HTTP server, a PB connection times
out.
"""
result = Deferred()
site = Site(Data("", "text/plain"))
client = HangCheckFactory(
PBClientFactory(), lambda: result.callback(None))
self.patch(HangCheckProtocol, '_HUNG_CONNECTION_TIMEOUT', 0.1)
connected_server_and_client(
self, site, client,
)
timer = reactor.callLater(2, result.cancel)
result.addCallback(lambda _: timer.cancel())
def check_for_timeout(reason):
reason.trap(CancelledError)
raise Exception("Didn't not hangup")
result.addErrback(check_for_timeout)
return result
示例6: testChildResolve
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def testChildResolve(self):
# I've seen problems with reactor.run under gtk2reactor. Spawn a
# child which just does reactor.resolve after the reactor has
# started, fail if it does not complete in a timely fashion.
helperPath = os.path.abspath(self.mktemp())
helperFile = open(helperPath, 'w')
# Eeueuuggg
reactorName = reactor.__module__
helperFile.write(resolve_helper % {'reactor': reactorName})
helperFile.close()
env = os.environ.copy()
env['PYTHONPATH'] = os.pathsep.join(sys.path)
helperDeferred = Deferred()
helperProto = ChildResolveProtocol(helperDeferred)
reactor.spawnProcess(helperProto, sys.executable, ("python", "-u", helperPath), env)
def cbFinished((reason, output, error)):
# If the output is "done 127.0.0.1\n" we don't really care what
# else happened.
output = ''.join(output)
if output != 'done 127.0.0.1\n':
self.fail((
"The child process failed to produce the desired results:\n"
" Reason for termination was: %r\n"
" Output stream was: %r\n"
" Error stream was: %r\n") % (reason.getErrorMessage(), output, ''.join(error)))
helperDeferred.addCallback(cbFinished)
return helperDeferred
示例7: run
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def run(self, regionEnd):
regionStart = 9000
log.msg("[NAT] Check Start")
d = Deferred()
d.addCallback(self.allEstablished)
self.ports2 = None
if regionStart != regionEnd and regionEnd >= 9000:
self.ports2 = [8002, 8003, 8004, regionStart, regionEnd]
else:
self.ports2 = [8002, 8003, 8004, regionStart]
self.ports = []
self.processports = []
for port in self.ports2:
hasProcessRunning = False
for name in self.clientObject.processes:
process = self.clientObject.processes[name]
if process.consolePort == port + 10000:
hasProcessRunning = True
if process.consolePort == 18000:
if port == 8002 or port == 8003 or port == 8004:
hasProcessRunning = True
if not hasProcessRunning:
self.ports += [port]
else:
if port == 8002:
self.processports += [18000]
elif port != 8003 and port != 8004: # We only want ROBUST once.
self.processports += [port + 10000]
self.count = len(self.ports)
self.service.start(d, self.count, self.ports)
示例8: test_json
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def test_json(self):
deferred = Deferred()
deferred.addCallback(lambda _: self.callbacks.add("success"))
deferred.addErrback(lambda _: self.callbacks.add("failure"))
twisted_headers = Headers({"Content-Type": ["application/json"]})
twisted_response = TWResponse(
("HTTP", 1, 1), 200, "OK", twisted_headers, None)
request = Request(
method="GET", url="/",
kwargs={
"headers": {
"Content-Type": "application/json"}, "data": None})
data = {
os.urandom(6).encode("hex"): os.urandom(6).encode("hex"),
os.urandom(6).encode("hex"): os.urandom(6).encode("hex")
}
r = Response(deferred, twisted_response, request)
map(r.dataReceived, json.dumps(data))
r.connectionLost(responseDone)
self.assertEqual(self.callbacks, set(["success"]))
self.assertTrue(r._done)
self.assertEqual(r.json(), data)
return deferred
示例9: test_disorderlyShutdown
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def test_disorderlyShutdown(self):
"""
If a L{TLSMemoryBIOProtocol} loses its connection unexpectedly, this is
reported to the application.
"""
clientConnectionLost = Deferred()
clientFactory = ClientFactory()
clientFactory.protocol = (
lambda: ConnectionLostNotifyingProtocol(
clientConnectionLost))
clientContextFactory = HandshakeCallbackContextFactory()
wrapperFactory = TLSMemoryBIOFactory(
clientContextFactory, True, clientFactory)
sslClientProtocol = wrapperFactory.buildProtocol(None)
# Client speaks first, so the server can be dumb.
serverProtocol = Protocol()
connectionDeferred = loopbackAsync(serverProtocol, sslClientProtocol)
# Now destroy the connection.
serverProtocol.transport.loseConnection()
# And when the connection completely dies, check the reason.
def cbDisconnected(clientProtocol):
clientProtocol.lostConnectionReason.trap(Error)
clientConnectionLost.addCallback(cbDisconnected)
return clientConnectionLost
示例10: get_response
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def get_response(cmd_data):
for cmd in cmd_data :
def __command_done(result, command) :
res = result
if not isinstance(result, CommandResult) :
res = CommandResult(status = result)
self.factory.next_state(ProtocolState.Report, ReportData(command, res), self.transport.connector)
ok_func = partial(__command_done, command = cmd)
def __command_error(reason, command):
res = CommandResult('Failed', str(reason))
self.factory.next_state(ProtocolState.Report, ReportData(command, res), self.transport.connector)
err_func = partial(__command_error, command = cmd)
# Obtain only new commands next time
if self.factory.timestamp is not None :
self.factory.timestamp = max(self.factory.timestamp, self._parse_date(cmd['timestamp']))
else :
self.factory.timestamp = self._parse_date(cmd['timestamp'])
# DeviceDelegate has to use this deferred object to notify us that command processing finished.
cmd_defer = Deferred()
cmd_defer.addCallback(ok_func)
cmd_defer.addErrback(err_func)
# Actual run of command
try :
self.factory.device_delegate.do_command(cmd, cmd_defer)
except Exception, err :
log.err('Failed to execute device-delegate do_command. Reason: <{0}>.'.format(err))
err_func(err)
示例11: outer_callback_1
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def outer_callback_1(res):
print 'In outer_callback_1'
d = Deferred()
d.addCallback(inner_callback_1)
d.addCallback(inner_callback_2)
d.callback(0)
return d
示例12: callRemote
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def callRemote(self, _name, *args, **kw):
""" Make a call to the RemoteReference and return the result as a
Deferred. It exists to allow queuing of calls to remote reference
before the remote reference has arrived.
For more information refer to twisted.spread.pb.RemoteReference.
@param _name: Name of the method which should be called.
The prefix 'remote_' will be added to the name
in the remote object to select the method which
should be called.
@type _name: str
@param *args: Positional arguments which will be passed to
the remote method.
@param **kw: Keyworded arguments which will be passed to the
remote method.
@return: Deferred which will fire with the result of the
call or a Failure if there was a problem.
@rtype: twisted.internet.defer.Deferred
"""
if self.__failure is not None:
d = fail(self.__failure)
elif self.__pending is not None:
d = Deferred()
self.__pending.append(d)
else:
d = succeed(self.__obj)
d.addCallback(lambda ref: ref.callRemote(_name, *args, **kw))
d.addErrback(self.__filter, _name)
return d
示例13: cbRequest
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def cbRequest(response):
finished = Deferred()
finished.addCallback(cb)
finished.addErrback(err)
response.deliverBody(BufferedReception(finished))
cli.inflight -= 1
return finished
示例14: cbGetFirstCookie
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def cbGetFirstCookie(self, response):
onet_ubi_cookie = response.headers.getRawHeaders("Set-Cookie")[0]
onetzuo_ticket_cookie = response.headers.getRawHeaders("Set-Cookie")[1]
onet_cid_cookie = response.headers.getRawHeaders("Set-Cookie")[2]
# onet_sgn_cookie = response.headers.getRawHeaders('Set-Cookie')[3]
onet_ubi_match = re.search("onet_ubi=(.*?);", onet_ubi_cookie)
if onet_ubi_match:
onet_ubi_result = onet_ubi_match.group()
else:
onet_ubi_result = None
onetzuo_ticket_match = re.search("onetzuo_ticket=(.*?);", onetzuo_ticket_cookie)
if onetzuo_ticket_match:
onetzuo_ticket_result = onetzuo_ticket_match.group()
else:
onetzuo_ticket_result = None
onet_cid_match = re.search("onet_cid=(.*?);", onet_cid_cookie)
if onet_cid_match:
onet_cid_result = onet_cid_match.group()
else:
onet_cid_result = None
if onet_ubi_result != None and onetzuo_ticket_result != None and onet_cid_result != None:
finished = Deferred()
response.deliverBody(BeginningPrinter(finished))
finished.addCallback(self.cbGetFirstCookieSuccess, onet_ubi_result, onetzuo_ticket_result, onet_cid_result)
finished.addErrback(self.cbShutdown)
return finished
else:
self.authorise()
示例15: write
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallback [as 别名]
def write(res):
request.code = res.code
old_headers = request.responseHeaders
request.responseHeaders = res.headers
request.responseHeaders.setRawHeaders(
'content-encoding',
old_headers.getRawHeaders('content-encoding', []))
if not self._anonymous:
request.responseHeaders.addRawHeader("X-Proxied-By",
__version__.package + " " + __version__.base())
if request.isSecure() and host["sendhsts"]:
request.responseHeaders.setRawHeaders("Strict-Transport-Security",
["max-age=31536000"])
if self._clacks:
request.responseHeaders.addRawHeader("X-Clacks-Overhead",
"GNU Terry Pratchett")
for name, values in self._extraHeaders:
request.responseHeaders.setRawHeaders(name, values)
f = Deferred()
res.deliverBody(Downloader(f, request.write))
f.addCallback(lambda _: request.finish())
return f