本文整理汇总了Python中twisted.internet.defer.maybeDeferred方法的典型用法代码示例。如果您正苦于以下问题:Python defer.maybeDeferred方法的具体用法?Python defer.maybeDeferred怎么用?Python defer.maybeDeferred使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.defer
的用法示例。
在下文中一共展示了defer.maybeDeferred方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __call__
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
def __call__(self, event):
event = dict(event)
ra = event['a']
kw = event['kw']
if 'ra' in event and self in PacketEventHandler.function_w_rules:
ra = event['ra']
kw = event['rkw']
a = maybeDeferred(self.function, *ra, **kw)
def err(x):
a = x.getTraceback().split('\n')
self.x.logger.error("Error executing method - {} : {}".format(self.function.__name__, x.getErrorMessage() + "["+ a[-2].strip() + ' in ' + a[-4].strip() +"]"))
x.printDetailedTraceback()
a.addErrback(err)
return a
示例2: _cbSelectWork
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
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)
示例3: _cbTestPartialAppend
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
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
示例4: __call__
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
def __call__(self):
def cb(result):
if self.running:
self._scheduleFrom(self.clock.seconds())
else:
d, self._deferred = self._deferred, None
d.callback(self)
def eb(failure):
self.running = False
d, self._deferred = self._deferred, None
d.errback(failure)
self.call = None
d = defer.maybeDeferred(self.f, *self.a, **self.kw)
d.addCallback(cb)
d.addErrback(eb)
示例5: requestAvatarId
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
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)
# For backwards compatibility
# Allow access as the old name.
示例6: _runSequentially
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
def _runSequentially(callables, stopOnFirstError=False):
"""
Run the given callables one after the other. If a callable returns a
Deferred, wait until it has finished before running the next callable.
@param callables: An iterable of callables that take no parameters.
@param stopOnFirstError: If True, then stop running callables as soon as
one raises an exception or fires an errback. False by default.
@return: A L{Deferred} that fires a list of C{(flag, value)} tuples. Each
tuple will be either C{(SUCCESS, <return value>)} or C{(FAILURE,
<Failure>)}.
"""
results = []
for f in callables:
d = defer.maybeDeferred(f)
try:
thing = yield d
results.append((defer.SUCCESS, thing))
except Exception:
results.append((defer.FAILURE, Failure()))
if stopOnFirstError:
break
defer.returnValue(results)
示例7: test_assertFailure_masked
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
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 = pyunit.TestResult()
test.run(result)
self.assertEqual(1, len(result.failures))
示例8: validateTo
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
def validateTo(self, user):
"""
Validate the address for which a message is destined.
@type user: L{User}
@param user: The destination address.
@rtype: L{Deferred <defer.Deferred>} which successfully fires with
no-argument callable which returns L{IMessage <smtp.IMessage>}
provider.
@return: A deferred which successfully fires with a no-argument
callable which returns a message receiver for the destination.
@raise SMTPBadRcpt: When messages cannot be accepted for the
destination address.
"""
# XXX - Yick. This needs cleaning up.
if self.user and self.service.queue:
d = self.service.domains.get(user.dest.domain, None)
if d is None:
d = relay.DomainQueuer(self.service, True)
else:
d = self.service.domains[user.dest.domain]
return defer.maybeDeferred(d.exists, user)
示例9: do_APOP
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
def do_APOP(self, user, digest):
"""
Handle an APOP command.
Perform APOP authentication and complete the authorization process with
the L{_cbMailbox} callback function on success or the L{_ebMailbox}
and L{_ebUnexpected} errback functions on failure.
@type user: L{bytes}
@param user: A username.
@type digest: L{bytes}
@param digest: An MD5 digest string.
"""
d = defer.maybeDeferred(self.authenticateUserAPOP, user, digest)
d.addCallbacks(self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
).addErrback(self._ebUnexpected)
示例10: do_PASS
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
def do_PASS(self, password):
"""
Handle a PASS command.
If a USER command was previously received, authenticate the user and
complete the authorization process with the L{_cbMailbox} callback
function on success or the L{_ebMailbox} and L{_ebUnexpected} errback
functions on failure. If a USER command was not previously received,
send an error response.
@type password: L{bytes}
@param password: A password.
"""
if self._userIs is None:
self.failResponse("USER required before PASS")
return
user = self._userIs
self._userIs = None
d = defer.maybeDeferred(self.authenticateUserPASS, user, password)
d.addCallbacks(self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
).addErrback(self._ebUnexpected)
示例11: do_MAIL
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
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 as e:
self.sendCode(553, str(e))
return
validated = defer.maybeDeferred(self.validateFrom, self._helo, addr)
validated.addCallbacks(self._cbFromValidate, self._ebFromValidate)
示例12: do_RCPT
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
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 as e:
self.sendCode(553, str(e))
return
d = defer.maybeDeferred(self.validateTo, user)
d.addCallbacks(
self._cbToValidate,
self._ebToValidate,
callbackArgs=(user,)
)
示例13: __doCommand
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
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)
示例14: login
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
def login(self, username, password):
"""
Authenticate with the server using a username and password
This command is allowed in the Non-Authenticated state. If the
server supports the STARTTLS capability and our transport supports
TLS, TLS is negotiated before the login command is issued.
A more secure way to log in is to use C{startTLS} or
C{authenticate} or both.
@type username: L{str}
@param username: The username to log in with
@type password: L{str}
@param password: The password to log in with
@rtype: C{Deferred}
@return: A deferred whose callback is invoked if login is successful
and whose errback is invoked otherwise.
"""
d = maybeDeferred(self.getCapabilities)
d.addCallback(self.__cbLoginCaps, username, password)
return d
示例15: requestAvatarId
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import maybeDeferred [as 别名]
def requestAvatarId(self, credentials):
"""
Part of the L{ICredentialsChecker} interface. Called by a portal with
some credentials to check if they'll authenticate a user. We check the
interfaces that the credentials provide against our list of acceptable
checkers. If one of them matches, we ask that checker to verify the
credentials. If they're valid, we call our L{_cbGoodAuthentication}
method to continue.
@param credentials: the credentials the L{Portal} wants us to verify
"""
ifac = providedBy(credentials)
for i in ifac:
c = self.checkers.get(i)
if c is not None:
d = defer.maybeDeferred(c.requestAvatarId, credentials)
return d.addCallback(self._cbGoodAuthentication,
credentials)
return defer.fail(UnhandledCredentials("No checker for %s" % \
', '.join(map(reflect.qual, ifac))))