我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用twisted.internet.defer.maybeDeferred()。
def as_view(path): def decorator(func): # .. path_name, klass_name = (path.split(':')) # ... @inlineCallbacks def wrapper(router, request, *args, **kwargs): # ... module = importlib.import_module(path_name) Klass = getattr(module,klass_name) klass = Klass(router, request,*args, **kwargs) # .. result = yield defer.maybeDeferred(klass) defer.returnValue(result) # .. # _conspect_name(wrapper, klass_name) _conspect_name(wrapper, func.__name__) _conspect_param(wrapper, func) _conspect_param_defaults(wrapper, func) return wrapper return decorator
def call(self, request): # ... self._init_request_resource(request) self._init_request_method(request) # ... rdata = yield self._init_json_data(request) # ... params = self._get_params(rdata) method = self._get_method(rdata) # .. result = yield defer.maybeDeferred(method, request, **params) result = self._make_result(result) # ... defer.returnValue(result) # ..init # ==================================
def lineReceived(self, line): self.resetTimeout() def processFailed(err): #if err.check(FTPCmdError): # self.sendLine(err.value.response()) #else: log.msg("Unexpected FTP error") log.err(err) def processSucceeded(result): if isinstance(result, tuple): self.reply(*result) elif result is not None: self.reply(result) d = defer.maybeDeferred(self.processCommand, line) d.addCallbacks(processSucceeded, processFailed) d.addErrback(log.err)
def packet_CLOSE(self, data): requestId = data[:4] data = data[4:] handle, data = getNS(data) assert data == '', 'still have data in CLOSE: %s' % repr(data) if handle in self.openFiles: fileObj = self.openFiles[handle] d = defer.maybeDeferred(fileObj.close) d.addCallback(self._cbClose, handle, requestId) d.addErrback(self._ebStatus, requestId, "close failed") elif handle in self.openDirs: dirObj = self.openDirs[handle][0] d = defer.maybeDeferred(dirObj.close) d.addCallback(self._cbClose, handle, requestId, 1) d.addErrback(self._ebStatus, requestId, "close failed") else: self._ebClose(failure.Failure(KeyError()), requestId)
def testStartStop(self): client = Client() d = client.startedDeferred = defer.Deferred() port2 = reactor.connectUDP("127.0.0.1", 8888, client) def assertName(): self.failUnless(repr(port2).find('test_udp.Client') >= 0) def cbStarted(ignored): self.assertEquals(client.started, 1) self.assertEquals(client.stopped, 0) assertName() d = defer.maybeDeferred(port2.stopListening) d.addCallback(lambda ign: assertName()) return d return d.addCallback(cbStarted)
def testRegularFunction(self): s = SimpleProtocol() c = SimpleProtocol() def sendALine(result): s.sendLine("THIS IS LINE ONE!") s.transport.loseConnection() s.conn.addCallback(sendALine) def check(ignored): self.assertEquals(c.lines, ["THIS IS LINE ONE!"]) self.assertEquals(len(s.connLost), 1) self.assertEquals(len(c.connLost), 1) d = defer.maybeDeferred(self.loopbackFunc, s, c) d.addCallback(check) return d
def testSneakyHiddenDoom(self): s = DoomProtocol() c = DoomProtocol() def sendALine(result): s.sendLine("DOOM LINE") s.conn.addCallback(sendALine) def check(ignored): self.assertEquals(s.lines, ['Hello 1', 'Hello 2', 'Hello 3']) self.assertEquals(c.lines, ['DOOM LINE', 'Hello 1', 'Hello 2', 'Hello 3']) self.assertEquals(len(s.connLost), 1) self.assertEquals(len(c.connLost), 1) d = defer.maybeDeferred(self.loopbackFunc, s, c) d.addCallback(check) return d
def testMaybeDeferred(self): S, E = [], [] d = defer.maybeDeferred((lambda x: x + 5), 10) d.addCallbacks(S.append, E.append) self.assertEquals(E, []) self.assertEquals(S, [15]) S, E = [], [] try: '10' + 5 except TypeError, e: expected = str(e) d = defer.maybeDeferred((lambda x: x + 5), '10') d.addCallbacks(S.append, E.append) self.assertEquals(S, []) self.assertEquals(len(E), 1) self.assertEquals(str(E[0].value), expected) d = defer.Deferred() reactor.callLater(0.2, d.callback, 'Success') d.addCallback(self.assertEquals, 'Success') d.addCallback(self._testMaybeError) return d
def test_assertFailure_masked(self): """A single wrong assertFailure should fail the whole test. """ class ExampleFailure(Exception): pass class TC(unittest.TestCase): failureException = ExampleFailure def test_assertFailure(self): d = defer.maybeDeferred(lambda: 1/0) self.assertFailure(d, OverflowError) self.assertFailure(d, ZeroDivisionError) return d test = TC('test_assertFailure') result = reporter.TestResult() test.run(result) self.assertEqual(1, len(result.failures))
def requestAvatarId(self, c): try: u, p = self.getUser(c.username) except KeyError: return defer.fail(error.UnauthorizedLogin()) else: up = credentials.IUsernamePassword(c, None) if self.hash: if up is not None: h = self.hash(up.username, up.password, p) if h == p: return defer.succeed(u) return defer.fail(error.UnauthorizedLogin()) else: return defer.maybeDeferred(c.checkPassword, p ).addCallback(self._cbPasswordMatch, u)
def dispatchCommand(self, box): """ A box with a _command key was received. Dispatch it to a local handler call it. @param proto: an AMP instance. @param box: an AmpBox to be dispatched. """ cmd = box[COMMAND] fObj = self.lookupFunction(cmd) if fObj is None: return fail(RemoteAmpError( UNHANDLED_ERROR_CODE, "Unhandled Command: %r" % (cmd,), False, local=Failure(UnhandledCommand()))) return maybeDeferred(fObj, box)
def __doCommand(self, tag, handler, args, parseargs, line, uid): for (i, arg) in enumerate(parseargs): if callable(arg): parseargs = parseargs[i+1:] maybeDeferred(arg, self, line).addCallback( self.__cbDispatch, tag, handler, args, parseargs, uid).addErrback(self.__ebDispatch, tag) return else: args.append(arg) if line: # Too many arguments raise IllegalClientResponse("Too many arguments for command: " + repr(line)) if uid is not None: handler(uid=uid, *args) else: handler(*args)
def do_MAIL(self, rest): if self._from: self.sendCode(503,"Only one sender per message, please") return # Clear old recipient list self._to = [] m = self.mail_re.match(rest) if not m: self.sendCode(501, "Syntax error") return try: addr = Address(m.group('path'), self.host) except AddressError, e: self.sendCode(553, str(e)) return validated = defer.maybeDeferred(self.validateFrom, self._helo, addr) validated.addCallbacks(self._cbFromValidate, self._ebFromValidate)
def do_RCPT(self, rest): if not self._from: self.sendCode(503, "Must have sender before recipient") return m = self.rcpt_re.match(rest) if not m: self.sendCode(501, "Syntax error") return try: user = User(m.group('path'), self._helo, self, self._from) except AddressError, e: self.sendCode(553, str(e)) return d = defer.maybeDeferred(self.validateTo, user) d.addCallbacks( self._cbToValidate, self._ebToValidate, callbackArgs=(user,) )
def render(self, request): def finish(x): if request.channel is None: # disconnected return if x is not None: request.write(x) request.finish() def finish_error(fail): if request.channel is None: # disconnected return request.setResponseCode(500) # won't do anything if already written to request.write('---ERROR---') request.finish() log.err(fail, "Error in DeferredResource handler:") defer.maybeDeferred(resource.Resource.render, self, request).addCallbacks(finish, finish_error) return server.NOT_DONE_YET
def _cbTestPartialAppend(self, fetched, infile): fetched = list(fetched) self.assertTrue(len(fetched) == 1) self.assertTrue(len(fetched[0]) == 2) uid, msg = fetched[0] parsed = self.parser.parse(open(infile)) expected_body = parsed.get_payload() def assert_flags(flags): self.assertEqual( set((['\\SEEN'])), set(flags)) def assert_body(body): gotbody = body.read() self.assertEqual(expected_body, gotbody) d = defer.maybeDeferred(msg.getFlags) d.addCallback(assert_flags) d.addCallback(lambda _: defer.maybeDeferred(msg.getBodyFile)) d.addCallback(assert_body) return d
def _cbSelectWork(self, mbox, cmdName, tag): """ Callback for selectWork * patched to avoid conformance errors due to incomplete UIDVALIDITY line. * patched to accept deferreds for messagecount and recent count """ if mbox is None: self.sendNegativeResponse(tag, 'No such mailbox') return if '\\noselect' in [s.lower() for s in mbox.getFlags()]: self.sendNegativeResponse(tag, 'Mailbox cannot be selected') return d1 = defer.maybeDeferred(mbox.getMessageCount) d2 = defer.maybeDeferred(mbox.getRecentCount) d3 = defer.maybeDeferred(mbox.getUIDNext) return defer.gatherResults([d1, d2, d3]).addCallback( self.__cbSelectWork, mbox, cmdName, tag)
def fetch_if_new(self, result, task_info): job_id = task_info['job_id'] if result: log.debug("Task Result already exists: %s" % job_id) file_name = result['result_url'] self.task_storage.set_jobid_result_url(job_id, file_name) dfd = defer.maybeDeferred(self.publish_result, file_name, task_info) else: dfd = defer.maybeDeferred(self.fetcher.fetch, task_info['fetch_uri']) # get file response body dfd.addCallbacks(self.parse_response, self.failed, callbackArgs=(job_id,), errbackArgs=(job_id,)) # Save File dfd.addCallbacks(self.save_file_content, self.failed, callbackArgs=(job_id,), errbackArgs=(job_id,)) # Callback to URI dfd.addCallbacks(self.publish_result, self.failed, callbackArgs=(task_info,), errbackArgs=(job_id,))
def stopService(self): def stop_cb(): if self._connector is not None: self._connector.disconnect() del self._connector service.Service.stopService(self) l = [] for svc in reversed(list(self)): l.append(defer.maybeDeferred(svc.stopService)) if l: l = defer.DeferredList(l) l.addCallback(stop_cb) else: stop_cb() return l
def _runResponse(self, evt): """Passes on a response from the net thread. Called from wx main loop on reception of an wxEVT_RESPONSE""" d = maybeDeferred(evt.func, *evt.params, **evt.kwparams) if evt.onSuccess: def onDone(r): simpleCommand((evt.onSuccess, (r,), {})) d.addCallback(onDone) if evt.onFailure: def onFail(r): simpleCommand((evt.onFailure, (r,), {})) d.addErrback(onFail) # Methods called from net thread
def _doRunCommand(self, tc): """Called in the net thread to execute a gui command""" # Run the command and get a deferred if tc.passTC: d = maybeDeferred(tc.command[0], tc, *tc.command[1], **tc.command[2]) else: d = maybeDeferred(tc.command[0], *tc.command[1], **tc.command[2]) if tc.onSuccess: d.addCallback(self._success, tc) if tc.onFailure: d.addErrback(self._failure, tc)
def add(self, user): assert iwords.IChatClient.providedBy(user), "%r is not a chat client" % (user,) if user.name not in self.users: additions = [] self.users[user.name] = user for p in self.users.itervalues(): if p is not user: d = defer.maybeDeferred(p.userJoined, self, user) d.addErrback(self._ebUserCall, p=p) additions.append(d) defer.DeferredList(additions).addCallback(self._cbUserCall) return defer.succeed(None)
def remove(self, user, reason=None): assert reason is None or isinstance(reason, unicode) try: del self.users[user.name] except KeyError: pass else: removals = [] for p in self.users.itervalues(): if p is not user: d = defer.maybeDeferred(p.userLeft, self, user, reason) d.addErrback(self._ebUserCall, p=p) removals.append(d) defer.DeferredList(removals).addCallback(self._cbUserCall) return defer.succeed(None)
def receive(self, sender, recipient, message): assert recipient is self receives = [] for p in self.users.itervalues(): if p is not sender: d = defer.maybeDeferred(p.receive, sender, self, message) d.addErrback(self._ebUserCall, p=p) receives.append(d) defer.DeferredList(receives).addCallback(self._cbUserCall) return defer.succeed(None)
def setMetadata(self, meta): self.meta = meta sets = [] for p in self.users.itervalues(): d = defer.maybeDeferred(p.groupMetaUpdate, self, meta) d.addErrback(self._ebUserCall, p=p) sets.append(d) defer.DeferredList(sets).addCallback(self._cbUserCall) return defer.succeed(None)
def lineReceived(self, line): if self.client.transport.localClosed: return log.msg('got line %s' % repr(line)) line = line.lstrip() if not line: self._newLine() return if self.file and line.startswith('-'): self.ignoreErrors = 1 line = line[1:] else: self.ignoreErrors = 0 if ' ' in line: command, rest = line.split(' ', 1) rest = rest.lstrip() else: command, rest = line, '' if command.startswith('!'): # command f = self.cmd_EXEC rest = (command[1:] + ' ' + rest).strip() else: command = command.upper() log.msg('looking up cmd %s' % command) f = getattr(self, 'cmd_%s' % command, None) if f is not None: d = defer.maybeDeferred(f, rest) d.addCallback(self._cbCommand) d.addErrback(self._ebCommand) else: self._ebCommand(failure.Failure(NotImplementedError( "No command called `%s'" % command))) self._newLine()
def packet_OPEN(self, data): requestId = data[:4] data = data[4:] filename, data = getNS(data) flags ,= struct.unpack('!L', data[:4]) data = data[4:] attrs, data = self._parseAttributes(data) assert data == '', 'still have data in OPEN: %s' % repr(data) d = defer.maybeDeferred(self.client.openFile, filename, flags, attrs) d.addCallback(self._cbOpenFile, requestId) d.addErrback(self._ebStatus, requestId, "open failed")
def packet_READ(self, data): requestId = data[:4] data = data[4:] handle, data = getNS(data) (offset, length), data = struct.unpack('!QL', data[:12]), data[12:] assert data == '', 'still have data in READ: %s' % repr(data) if handle not in self.openFiles: self._ebRead(failure.Failure(KeyError()), requestId) else: fileObj = self.openFiles[handle] d = defer.maybeDeferred(fileObj.readChunk, offset, length) d.addCallback(self._cbRead, requestId) d.addErrback(self._ebStatus, requestId, "read failed")
def packet_WRITE(self, data): requestId = data[:4] data = data[4:] handle, data = getNS(data) offset, = struct.unpack('!Q', data[:8]) data = data[8:] writeData, data = getNS(data) assert data == '', 'still have data in WRITE: %s' % repr(data) if handle not in self.openFiles: self._ebWrite(failure.Failure(KeyError()), requestId) else: fileObj = self.openFiles[handle] d = defer.maybeDeferred(fileObj.writeChunk, offset, writeData) d.addCallback(self._cbStatus, requestId, "write succeeded") d.addErrback(self._ebStatus, requestId, "write failed")
def packet_RENAME(self, data): requestId = data[:4] data = data[4:] oldPath, data = getNS(data) newPath, data = getNS(data) assert data == '', 'still have data in RENAME: %s' % repr(data) d = defer.maybeDeferred(self.client.renameFile, oldPath, newPath) d.addCallback(self._cbStatus, requestId, "rename succeeded") d.addErrback(self._ebStatus, requestId, "rename failed")
def packet_MKDIR(self, data): requestId = data[:4] data = data[4:] path, data = getNS(data) attrs, data = self._parseAttributes(data) assert data == '', 'still have data in MKDIR: %s' % repr(data) d = defer.maybeDeferred(self.client.makeDirectory, path, attrs) d.addCallback(self._cbStatus, requestId, "mkdir succeeded") d.addErrback(self._ebStatus, requestId, "mkdir failed")
def packet_RMDIR(self, data): requestId = data[:4] data = data[4:] path, data = getNS(data) assert data == '', 'still have data in RMDIR: %s' % repr(data) d = defer.maybeDeferred(self.client.removeDirectory, path) d.addCallback(self._cbStatus, requestId, "rmdir succeeded") d.addErrback(self._ebStatus, requestId, "rmdir failed")
def packet_OPENDIR(self, data): requestId = data[:4] data = data[4:] path, data = getNS(data) assert data == '', 'still have data in OPENDIR: %s' % repr(data) d = defer.maybeDeferred(self.client.openDirectory, path) d.addCallback(self._cbOpenDirectory, requestId) d.addErrback(self._ebStatus, requestId, "opendir failed")
def packet_READDIR(self, data): requestId = data[:4] data = data[4:] handle, data = getNS(data) assert data == '', 'still have data in READDIR: %s' % repr(data) if handle not in self.openDirs: self._ebStatus(failure.Failure(KeyError()), requestId) else: dirObj, dirIter = self.openDirs[handle] d = defer.maybeDeferred(self._scanDirectory, dirIter, []) d.addCallback(self._cbSendDirectory, requestId) d.addErrback(self._ebStatus, requestId, "scan directory failed")
def packet_FSTAT(self, data): requestId = data[:4] data = data[4:] handle, data = getNS(data) assert data == '', 'still have data in FSTAT: %s' % repr(data) if handle not in self.openFiles: self._ebStatus(failure.Failure(KeyError('%s not in self.openFiles' % handle)), requestId) else: fileObj = self.openFiles[handle] d = defer.maybeDeferred(fileObj.getAttrs) d.addCallback(self._cbStat, requestId) d.addErrback(self._ebStatus, requestId, 'fstat failed')
def packet_SETSTAT(self, data): requestId = data[:4] data = data[4:] path, data = getNS(data) attrs, data = self._parseAttributes(data) if data != '': log.msg('WARN: still have data in SETSTAT: %s' % repr(data)) d = defer.maybeDeferred(self.client.setAttrs, path, attrs) d.addCallback(self._cbStatus, requestId, 'setstat succeeded') d.addErrback(self._ebStatus, requestId, 'setstat failed')
def packet_FSETSTAT(self, data): requestId = data[:4] data = data[4:] handle, data = getNS(data) attrs, data = self._parseAttributes(data) assert data == '', 'still have data in FSETSTAT: %s' % repr(data) if handle not in self.openFiles: self._ebStatus(failure.Failure(KeyError()), requestId) else: fileObj = self.openFiles[handle] d = defer.maybeDeferred(fileObj.setAttrs, attrs) d.addCallback(self._cbStatus, requestId, 'fsetstat succeeded') d.addErrback(self._ebStatus, requestId, 'fsetstat failed')
def packet_READLINK(self, data): requestId = data[:4] data = data[4:] path, data = getNS(data) assert data == '', 'still have data in READLINK: %s' % repr(data) d = defer.maybeDeferred(self.client.readLink, path) d.addCallback(self._cbReadLink, requestId) d.addErrback(self._ebStatus, requestId, 'readlink failed')
def packet_SYMLINK(self, data): requestId = data[:4] data = data[4:] linkPath, data = getNS(data) targetPath, data = getNS(data) d = defer.maybeDeferred(self.client.makeLink, linkPath, targetPath) d.addCallback(self._cbStatus, requestId, 'symlink succeeded') d.addErrback(self._ebStatus, requestId, 'symlink failed')
def packet_EXTENDED(self, data): requestId = data[:4] data = data[4:] extName, extData = getNS(data) d = defer.maybeDeferred(self.client.extendedRequest, extName, extData) d.addCallback(self._cbExtended, requestId) d.addErrback(self._ebStatus, requestId, 'extended %s failed' % extName)
def msg_requestReceived(self, lst): channelID, requestType, data = lst d = defer.maybeDeferred(self.channels[channelID].requestReceived, requestType, data) self.returnDeferredWire(d)
def tearDown(self): try: self.fac.proto.done = 1 except AttributeError: pass else: self.fac.proto.transport.loseConnection() return defer.maybeDeferred(self.server.stopListening)
def testLocalToRemoteForwarding(self): f = EchoFactory() f.fac = self.fac serv = reactor.listenTCP(0, f) port = serv.getHost().port lport = self._getRandomPort() d = defer.Deferred() d.addCallback(lambda x : defer.maybeDeferred(serv.stopListening)) p = ConchTestForwardingProcess(d, lport,self.fac) return self.execute('', p, preargs='-N -L%i:127.0.0.1:%i' % (lport, port))
def testRemoteToLocalForwarding(self): f = EchoFactory() f.fac = self.fac serv = reactor.listenTCP(0, f) port = serv.getHost().port lport = self._getRandomPort() d = defer.Deferred() d.addCallback(lambda x : defer.maybeDeferred(serv.stopListening)) p = ConchTestForwardingProcess(d, lport, self.fac) return self.execute('', p, preargs='-N -R %i:127.0.0.1:%i' % (lport, port))
def stopServer(self): if not hasattr(self.server.factory, 'proto'): return self._cbStopServer(None) self.server.factory.proto.expectedLoseConnection = 1 d = defer.maybeDeferred( self.server.factory.proto.transport.loseConnection) d.addCallback(self._cbStopServer) return d
def _cbStopServer(self, ignored): return defer.maybeDeferred(self.server.stopListening)
def tearDown(self): d = defer.maybeDeferred(self.conn.transport.loseConnection) d.addCallback(lambda x : self.stopServer()) return d