我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用twisted.internet.defer.fail()。
def _response(self, _, driver, spider): body = driver.execute_script('return document.documentElement.innerHTML') if body.startswith( "<head></head>"): # selenium ????http??????,???????????????,????body??????<head></head>???,?????? body = driver.execute_script('return document.documentElement.textContent') url = driver.current_url respcls = responsetypes.from_args(url=url, body=body[:100].encode('utf-8')) response = respcls(url=url, body=body, encoding='utf-8') response_failed = getattr(spider, 'response_failed', None) if response_failed and callable(response_failed) and response_failed(response, driver): driver.quit() return defer.fail(Failure()) else: self.queue.put(driver) # ?driver????queue return defer.succeed(response) # ??response??
def _pamConv(self, items): resp = [] for message, kind in items: if kind == 1: # password resp.append((message, 0)) elif kind == 2: # text resp.append((message, 1)) elif kind in (3, 4): return defer.fail(error.ConchError('cannot handle PAM 3 or 4 messages')) else: return defer.fail(error.ConchError('bad PAM auth kind %i' % kind)) packet = NS('')+NS('')+NS('') packet += struct.pack('>L', len(resp)) for prompt, echo in resp: packet += NS(prompt) packet += chr(echo) self.transport.sendPacket(MSG_USERAUTH_INFO_REQUEST, packet) self._pamDeferred = defer.Deferred() return self._pamDeferred
def getPrivateKey(self): file = os.path.expanduser(self.usedFiles[-1]) if not os.path.exists(file): return None try: return defer.succeed(keys.getPrivateKeyObject(file)) except keys.BadKeyError, e: if e.args[0] == 'encrypted key with no passphrase': for i in range(3): prompt = "Enter passphrase for key '%s': " % \ self.usedFiles[-1] try: p = self._getPassword(prompt) return defer.succeed(keys.getPrivateKeyObject(file, passphrase = p)) except (keys.BadKeyError, ConchError): pass return defer.fail(ConchError('bad password')) raise except KeyboardInterrupt: print reactor.stop()
def testStopOutstanding(self): """ Test that a running iterator paused on a third-party Deferred will properly stop when .stop() is called. """ testControlD = defer.Deferred() outstandingD = defer.Deferred() def myiter(): reactor.callLater(0, testControlD.callback, None) yield outstandingD self.fail() c = task.Cooperator() d = c.coiterate(myiter()) def stopAndGo(ign): c.stop() outstandingD.callback('arglebargle') testControlD.addCallback(stopAndGo) d.addCallback(self.cbIter) d.addErrback(self.ebIter) return d.addCallback(lambda result: self.assertEquals(result, self.RESULT))
def testWakerOverflow(self): self.failure = None waiter = threading.Event() def threadedFunction(): # Hopefully a hundred thousand queued calls is enough to # trigger the error condition for i in xrange(100000): try: reactor.callFromThread(lambda: None) except: self.failure = failure.Failure() break waiter.set() reactor.callInThread(threadedFunction) waiter.wait(120) if not waiter.isSet(): self.fail("Timed out waiting for event") if self.failure is not None: return defer.fail(self.failure)
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 articleRequest(self, group, index, id = None): if id is not None: raise NotImplementedError if self.db.has_key(group): if self.db[group].has_key(index): a = self.db[group][index] return defer.succeed(( index, a.getHeader('Message-ID'), StringIO.StringIO(a.textHeaders() + '\r\n' + a.body) )) else: return defer.fail(ERR_NOARTICLE) else: return defer.fail(ERR_NOGROUP)
def articleRequest(self, group, index, id = None): if id is not None: try: xref = self.dbm['Message-IDs'][id] except KeyError: return defer.fail(NewsServerError("No such article: " + id)) else: group, index = xref[0] index = int(index) try: a = self.dbm['groups'][group].articles[index] except KeyError: return defer.fail(NewsServerError("No such group: " + group)) else: return defer.succeed(( index, a.getHeader('Message-ID'), StringIO.StringIO(a.textHeaders() + '\r\n' + a.body) ))
def headRequest(self, group, index, id = None): if id is not None: try: xref = self.dbm['Message-IDs'][id] except KeyError: return defer.fail(NewsServerError("No such article: " + id)) else: group, index = xref[0] index = int(index) try: a = self.dbm['groups'][group].articles[index] except KeyError: return defer.fail(NewsServerError("No such group: " + group)) else: return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders()))
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 defConv(items): resp = [] for i in range(len(items)): message, kind = items[i] if kind == 1: # password p = getpass.getpass(message) resp.append((p, 0)) elif kind == 2: # text p = raw_input(message) resp.append((p, 0)) elif kind in (3,4): print message resp.append(("", 0)) else: return defer.fail('foo') d = defer.succeed(resp) return d
def callRemote(self, name, *args, **kw): """Call a specially-designated local method. self.callRemote('x') will first try to invoke a method named sync_x and return its result (which should probably be a Deferred). Second, it will look for a method called async_x, which will be called and then have its result (or Failure) automatically wrapped in a Deferred. """ if hasattr(self, 'sync_'+name): return getattr(self, 'sync_'+name)(*args, **kw) try: method = getattr(self, "async_" + name) return defer.succeed(method(*args, **kw)) except: f = Failure() if self.reportAllTracebacks: f.printTraceback() return defer.fail(f)
def ftp_USER(self, username): """ First part of login. Get the username the peer wants to authenticate as. """ if not username: return defer.fail(CmdSyntaxError('USER requires an argument')) self._user = username self.state = self.INAUTH if self.factory.allowAnonymous and self._user == self.factory.userAnonymous: return GUEST_NAME_OK_NEED_EMAIL else: return (USR_NAME_OK_NEED_PASS, username) # TODO: add max auth try before timeout from ip... # TODO: need to implement minimal ABOR command
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 queryTCP(self, queries, timeout = 10): """ Make a number of DNS queries via TCP. @type queries: Any non-zero number of C{dns.Query} instances @param queries: The queries to make. @type timeout: C{int} @param timeout: The number of seconds after which to fail. @rtype: C{Deferred} """ if not len(self.connections): address = self.pickServer() if address is None: return defer.fail(IOError("No domain name servers available")) host, port = address from twisted.internet import reactor reactor.connectTCP(host, port, self.factory) self.pending.append((defer.Deferred(), queries, timeout)) return self.pending[-1][0] else: return self.connections[0].query(queries, timeout)
def lookupZone(self, name, timeout = 10): if self.soa[0].lower() == name.lower(): # Wee hee hee hooo yea default_ttl = max(self.soa[1].minimum, self.soa[1].expire) if self.soa[1].ttl is not None: soa_ttl = self.soa[1].ttl else: soa_ttl = default_ttl results = [dns.RRHeader(self.soa[0], dns.SOA, dns.IN, soa_ttl, self.soa[1], auth=True)] for (k, r) in self.records.items(): for rec in r: if rec.ttl is not None: ttl = rec.ttl else: ttl = default_ttl if rec.TYPE != dns.SOA: results.append(dns.RRHeader(k, rec.TYPE, dns.IN, ttl, rec, auth=True)) results.append(results[0]) return defer.succeed((results, (), ())) return defer.fail(failure.Failure(dns.DomainError(name)))
def _lookup(self, name, cls, type, timeout): now = time.time() q = dns.Query(name, type, cls) try: when, (ans, auth, add) = self.cache[q] except KeyError: if self.verbose > 1: log.msg('Cache miss for ' + repr(name)) return defer.fail(failure.Failure(dns.DomainError(name))) else: if self.verbose: log.msg('Cache hit for ' + repr(name)) diff = now - when return defer.succeed(( [dns.RRHeader(str(r.name), r.type, r.cls, r.ttl - diff, r.payload) for r in ans], [dns.RRHeader(str(r.name), r.type, r.cls, r.ttl - diff, r.payload) for r in auth], [dns.RRHeader(str(r.name), r.type, r.cls, r.ttl - diff, r.payload) for r in add] ))
def __cbAuthenticate(self, caps, secret): auths = caps.get('AUTH', ()) for scheme in auths: if scheme.upper() in self.authenticators: cmd = Command('AUTHENTICATE', scheme, (), self.__cbContinueAuth, scheme, secret) return self.sendCommand(cmd) if self.startedTLS: return defer.fail(NoSupportedAuthentication( auths, self.authenticators.keys())) else: def ebStartTLS(err): err.trap(IMAP4Exception) # We couldn't negotiate TLS for some reason return defer.fail(NoSupportedAuthentication( auths, self.authenticators.keys())) d = self.startTLS() d.addErrback(ebStartTLS) d.addCallback(lambda _: self.getCapabilities()) d.addCallback(self.__cbAuthTLS, secret) return d
def test_failureWithSuccessfulFallback(self): """ Test that if the MX record lookup fails, fallback is enabled, and an A record is available for the name, then the Deferred returned by L{MXCalculator.getMX} ultimately fires with a Record_MX instance which gives the address in the A record for the name. """ class DummyResolver(object): """ Fake resolver which will fail an MX lookup but then succeed a getHostByName call. """ def lookupMailExchange(self, domain): return defer.fail(DNSNameError()) def getHostByName(self, domain): return defer.succeed("1.2.3.4") self.mx.resolver = DummyResolver() d = self.mx.getMX("domain") d.addCallback(self.assertEqual, Record_MX(name="1.2.3.4")) return d
def _login(self, caps, username, password): if self.serverChallenge is not None: return self._apop(username, password, self.serverChallenge) tryTLS = 'STLS' in caps #If our transport supports switching to TLS, we might want to try to switch to TLS. tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None # If our transport is not already using TLS, we might want to try to switch to TLS. nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport: d = self.startTLS() d.addCallback(self._loginTLS, username, password) return d elif self.startedTLS or not nontlsTransport or self.allowInsecureLogin: return self._plaintext(username, password) else: return defer.fail(InsecureAuthenticationDisallowed())
def testExtractInvalidAttachedKey(self): KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n..." message = MIMEMultipart() message.add_header("from", ADDRESS_2) key = MIMEApplication("", "pgp-keys") key.set_payload(KEY) message.attach(key) self.fetcher._keymanager.put_raw_key = Mock( return_value=defer.fail(KeyAddressMismatch())) def put_raw_key_called(_): self.fetcher._keymanager.put_raw_key.assert_called_once_with( KEY, address=ADDRESS_2) d = self._do_fetch(message.as_string()) d.addCallback(put_raw_key_called) d.addErrback(log.err) return d
def testLogErrorIfDecryptFails(self): def assert_failure(_): mock_logger_error.assert_any_call('_decrypt_doc: ' 'Error decrypting document with ' 'ID 1') with patch.object(Logger, 'error') as mock_logger_error: doc = SoledadDocument() doc.doc_id = '1' doc.content = {'_enc_json': ''} self.fetcher._process_decrypted_doc = Mock() self.km.decrypt = Mock( return_value=defer.fail(Exception())) d = self.fetcher._decrypt_doc(doc) d.addCallback(assert_failure) return d
def checkSoledadToken(self, username, password, service): soledad = self._soledad_sessions.get(username) if not soledad: return defer.fail(Exception("No soledad")) def match_token(token): if token is None: raise RuntimeError('no token') if token == password: return username else: raise RuntimeError('bad token') d = soledad.get_or_create_service_token(service) d.addCallback(match_token) return d
def setUp(self): super(CloudTest, self).setUp() self.query_results = {} self.kwargs = {} def fetch_stub(url, **kwargs): self.kwargs = kwargs value = self.query_results[url] if isinstance(value, Exception): return fail(value) else: return succeed(value) self.fetch_func = fetch_stub self.add_query_result("instance-id", b"i00001") self.add_query_result("ami-id", b"ami-00002") self.add_query_result("instance-type", b"hs1.8xlarge")
def test_import_from_file_with_empty_client_section(self): old_configuration = "[client]\n" config_filename = self.makeFile("", old_configuration, basename="final_config") import_filename = self.makeFile("", basename="import_config") # Use a command line option as well to test the precedence. try: self.get_config(["--config", config_filename, "--silent", "--import", import_filename]) except ImportOptionError as error: self.assertEqual(str(error), "Nothing to import at %s." % import_filename) else: self.fail("ImportOptionError not raised")
def test_import_from_url_with_pycurl_error( self, mock_fetch, mock_print_text): mock_fetch.side_effect = PyCurlError(60, "pycurl message") config_filename = self.makeFile("", basename="final_config") try: self.get_config(["--config", config_filename, "--silent", "--import", "https://config.url"]) except ImportOptionError as error: self.assertEqual(str(error), "Couldn't download configuration from " "https://config.url: Error 60: pycurl message") else: self.fail("ImportOptionError not raised") mock_fetch.assert_called_once_with("https://config.url") mock_print_text.assert_called_once_with( "Fetching configuration from https://config.url...")
def test_register_registration_error(self): """ If we get a registration error, the register() function returns the error from the registration response message. """ self.reactor.call_later(0, self.reactor.fire, "registration-failed") def fail_register(): return fail(RegistrationError("max-pending-computers")) self.remote.register = fail_register connector_factory = FakeConnectorFactory(self.remote) result = register( config=self.config, reactor=self.reactor, connector_factory=connector_factory, max_retries=99) self.assertEqual("max-pending-computers", result)
def test_check_daemons(self): """ The daemons are checked to be running every so often. When N=5 of these checks fail, the daemon will be restarted. """ clock = Clock() dog = WatchDog(clock, broker=AsynchronousPingDaemon("test-broker"), monitor=AsynchronousPingDaemon("test-monitor"), manager=AsynchronousPingDaemon("test-manager")) dog.start_monitoring() for i in range(4): clock.advance(5) dog.broker.fire_running(False) dog.monitor.fire_running(True) dog.manager.fire_running(True) self.assertEqual(dog.broker.boots, []) clock.advance(5) dog.broker.fire_running(False) dog.monitor.fire_running(True) dog.manager.fire_running(True) self.assertEqual(dog.broker.boots, [STOP, START])
def test_verify_invalid_signature(self, gpg_mock): """ L{ReleaseUpgrader.verify} logs a warning in case the tarball signature is not valid. """ gpg_mock.return_value = fail(InvalidGPGSignature("gpg error")) tarball_filename = "/some/tarball" signature_filename = "/some/signature" result = self.upgrader.verify(tarball_filename, signature_filename) def check_failure(failure): self.assertIn("WARNING: Invalid signature for upgrade-tool " "tarball: gpg error", self.logfile.getvalue()) gpg_mock.assert_called_once_with( tarball_filename, signature_filename) result.addCallback(self.fail) result.addErrback(check_failure) return result
def request(self, method, uri, headers=None, bodyProducer=None): return fail(self.error)
def requestAvatarId(self, credentials): return defer.fail(error.UnauthorizedLogin())
def addUser(self, user): if user.name in self.users: return defer.fail(failure.Failure(ewords.DuplicateUser())) self.users[user.name] = user return defer.succeed(user)
def addGroup(self, group): if group.name in self.groups: return defer.fail(failure.Failure(ewords.DuplicateGroup())) self.groups[group.name] = group return defer.succeed(group)
def lookupUser(self, name): assert isinstance(name, unicode) name = name.lower() try: user = self.users[name] except KeyError: return defer.fail(failure.Failure(ewords.NoSuchUser(name))) else: return defer.succeed(user)
def lookupGroup(self, name): assert isinstance(name, unicode) name = name.lower() try: group = self.groups[name] except KeyError: return defer.fail(failure.Failure(ewords.NoSuchGroup(name))) else: return defer.succeed(group)
def start(self): """ Start SASL authentication exchange. Used the authenticator's C{jid} and C{password} attribute for the authentication credentials. If no supported SASL mechanisms are advertized by the receiving party, a failing deferred is returned with a L{SASLNoAcceptableMechanism} exception. """ jid = self.xmlstream.authenticator.jid password = self.xmlstream.authenticator.password mechanisms = get_mechanisms(self.xmlstream) if 'DIGEST-MD5' in mechanisms: self.mechanism = sasl_mechanisms.DigestMD5('xmpp', jid.host, None, jid.user, password) elif 'PLAIN' in mechanisms: self.mechanism = sasl_mechanisms.Plain(None, jid.user, password) else: return defer.fail(SASLNoAcceptableMechanism) self._deferred = defer.Deferred() self.xmlstream.addObserver('/challenge', self.onChallenge) self.xmlstream.addOnetimeObserver('/success', self.onSuccess) self.xmlstream.addOnetimeObserver('/failure', self.onFailure) self.sendAuth(self.mechanism.getInitialResponse()) return self._deferred
def verifyHostKey(self, pubKey, fingerprint): #d = defer.Deferred() #d.addCallback(lambda x:defer.succeed(1)) #d.callback(2) #return d goodKey = isInKnownHosts(options['host'], pubKey, {'known-hosts': None}) if goodKey == 1: # good key return defer.succeed(1) elif goodKey == 2: # AAHHHHH changed return defer.fail(error.ConchError('bad host key')) else: if options['host'] == self.transport.getPeer()[1]: host = options['host'] khHost = options['host'] else: host = '%s (%s)' % (options['host'], self.transport.getPeer()[1]) khHost = '%s,%s' % (options['host'], self.transport.getPeer()[1]) keyType = common.getNS(pubKey)[0] ques = """The authenticity of host '%s' can't be established.\r %s key fingerprint is %s.""" % (host, {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType], fingerprint) ques+='\r\nAre you sure you want to continue connecting (yes/no)? ' return deferredAskFrame(ques, 1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)
def verifyHostKey(self, hostKey, fingerprint): """Returns a Deferred that gets a callback if it is a valid key, or an errback if not. @type hostKey: C{str} @type fingerprint: C{str} @rtype: L{Deferred} """ # return if it's good return defer.fail(NotImplementedError)
def tryAuth(self, kind, user, data): log.msg('%s trying auth %s' % (user, kind)) if kind not in self.supportedAuthentications: return defer.fail(error.ConchError('unsupported authentication, failing')) kind = kind.replace('-', '_') f = getattr(self,'auth_%s'%kind, None) if f: ret = f(data) if not ret: return defer.fail(error.ConchError('%s return None instead of a Deferred' % kind)) else: return ret return defer.fail(error.ConchError('bad auth type: %s' % kind))
def ssh_USERAUTH_PK_OK(self, packet): if self.lastAuth == 'publickey': # this is ok publicKey = self.lastPublicKey keyType = getNS(publicKey)[0] b = NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) + \ NS(self.user) + NS(self.instance.name) + NS('publickey') + '\xff' +\ NS(keyType) + NS(publicKey) d = self.signData(publicKey, b) if not d: self.askForAuth('none', '') # this will fail, we'll move on return d.addCallback(self._cbSignedData) d.addErrback(self._ebAuth) elif self.lastAuth == 'password': prompt, language, rest = getNS(packet, 2) self._oldPass = self._newPass = None self.getPassword('Old Password: ').addCallbacks(self._setOldPass, self._ebAuth) self.getPassword(prompt).addCallbacks(self._setNewPass, self._ebAuth) elif self.lastAuth == 'keyboard-interactive': name, instruction, lang, data = getNS(packet, 3) numPrompts = struct.unpack('!L', data[:4])[0] data = data[4:] prompts = [] for i in range(numPrompts): prompt, data = getNS(data) echo = bool(ord(data[0])) data = data[1:] prompts.append((prompt, echo)) d = self.getGenericAnswers(name, instruction, prompts) d.addCallback(self._cbGenericAnswers) d.addErrback(self._ebAuth)
def getGenericAnswers(self, name, instruction, prompts): """ Returns a L{Deferred} with the responses to the promopts. @param name: The name of the authentication currently in progress. @param instruction: Describes what the authentication wants. @param prompts: A list of (prompt, echo) pairs, where prompt is a string to display and echo is a boolean indicating whether the user's response should be echoed as they type it. """ return defer.fail(NotImplementedError())
def msg_sendRequest(self, lst): cn, requestType, data, wantReply = lst if not self.haveChannel(cn): if wantReply: self.returnDeferredWire(defer.fail(ConchError("no channel"))) channel = self.getChannel(cn) d = self.conn.sendRequest(channel, requestType, data, wantReply) if wantReply: self.returnDeferredWire(d)
def connect(host, port, options, verifyHostKey, userAuthObject): if options['nocache']: return defer.fail(ConchError('not using connection caching')) d = defer.Deferred() filename = os.path.expanduser("~/.conch-%s-%s-%i" % (userAuthObject.user, host, port)) factory = SSHUnixClientFactory(d, options, userAuthObject) reactor.connectUNIX(filename, factory, timeout=2, checkPID=1) return d
def verifyHostKey(transport, host, pubKey, fingerprint): goodKey = isInKnownHosts(host, pubKey, transport.factory.options) if goodKey == 1: # good key return defer.succeed(1) elif goodKey == 2: # AAHHHHH changed return defer.fail(ConchError('changed host key')) else: oldout, oldin = sys.stdout, sys.stdin sys.stdin = sys.stdout = open('/dev/tty','r+') if host == transport.transport.getPeer().host: khHost = host else: host = '%s (%s)' % (host, transport.transport.getPeer().host) khHost = '%s,%s' % (host, transport.transport.getPeer().host) keyType = common.getNS(pubKey)[0] print """The authenticity of host '%s' can't be established. %s key fingerprint is %s.""" % (host, {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType], fingerprint) try: ans = raw_input('Are you sure you want to continue connecting (yes/no)? ') except KeyboardInterrupt: return defer.fail(ConchError("^C")) while ans.lower() not in ('yes', 'no'): ans = raw_input("Please type 'yes' or 'no': ") sys.stdout,sys.stdin=oldout,oldin if ans == 'no': print 'Host key verification failed.' return defer.fail(ConchError('bad host key')) print "Warning: Permanently added '%s' (%s) to the list of known hosts." % (khHost, {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType]) known_hosts = open(os.path.expanduser('~/.ssh/known_hosts'), 'r+') known_hosts.seek(-1, 2) if known_hosts.read(1) != '\n': known_hosts.write('\n') encodedKey = base64.encodestring(pubKey).replace('\n', '') known_hosts.write('%s %s %s\n' % (khHost, keyType, encodedKey)) known_hosts.close() return defer.succeed(1)
def requestAvatarId(self, credentials): if pwd: try: cryptedPass = pwd.getpwnam(credentials.username)[1] except KeyError: return defer.fail(UnauthorizedLogin()) else: if cryptedPass not in ['*', 'x'] and \ verifyCryptedPassword(cryptedPass, credentials.password): return defer.succeed(credentials.username) if shadow: gid = os.getegid() uid = os.geteuid() os.setegid(0) os.seteuid(0) try: shadowPass = shadow.getspnam(credentials.username)[1] except KeyError: os.setegid(gid) os.seteuid(uid) return defer.fail(UnauthorizedLogin()) os.setegid(gid) os.seteuid(uid) if verifyCryptedPassword(shadowPass, credentials.password): return defer.succeed(credentials.username) return defer.fail(UnauthorizedLogin()) return defer.fail(UnauthorizedLogin())
def requestAvatarId(self, credentials): ifac = interface.providedBy(credentials) for i in ifac: c = self.checkers.get(i) if c is not None: return c.requestAvatarId(credentials).addCallback( self._cbGoodAuthentication, credentials) return defer.fail(UnhandledCredentials("No checker for %s" % \ ', '.join(map(reflect.qal, ifac))))
def disableLocal(option): """Disable the given option locally. Unlike enableLocal, this method cannot fail. The option must be disabled. """
def do(option): """Indicate a desire for the peer to begin performing the given option. Returns a Deferred that fires with True when the peer begins performing the option, or False when the peer refuses to perform it. If the peer is already performing the given option, the Deferred will fail with L{AlreadyEnabled}. If a negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be enabled. """
def will(option): """Indicate our willingness to begin performing this option locally. Returns a Deferred that fires with True when the peer agrees to allow us to begin performing this option, or False if the peer refuses to allow us to begin performing it. If the option is already enabled locally, the Deferred will fail with L{AlreadyEnabled}. If negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be enabled. """