本文整理汇总了Python中twisted.python.context.call方法的典型用法代码示例。如果您正苦于以下问题:Python context.call方法的具体用法?Python context.call怎么用?Python context.call使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.python.context
的用法示例。
在下文中一共展示了context.call方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: callWithContext
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def callWithContext(self, newContext, func, *args, **kw):
"""
Call C{func(*args, **kw)} such that the contents of C{newContext} will
be available for it to retrieve using L{getContext}.
@param newContext: A C{dict} of data to push onto the context for the
duration of the call to C{func}.
@param func: A callable which will be called.
@param *args: Any additional positional arguments to pass to C{func}.
@param **kw: Any additional keyword arguments to pass to C{func}.
@return: Whatever is returned by C{func}
@raise: Whatever is raised by C{func}.
"""
self.contexts.append(newContext)
try:
return func(*args,**kw)
finally:
self.contexts.pop()
示例2: flushErrors
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def flushErrors(*errorTypes):
"""Support function for testing frameworks.
Return a list of errors that occurred since the last call to flushErrors().
(This will return None unless startKeepingErrors has been called.)
"""
global _keptErrors
k = _keptErrors
_keptErrors = []
if errorTypes:
for erk in k:
shouldReLog = 1
for errT in errorTypes:
if erk.check(errT):
shouldReLog = 0
if shouldReLog:
err(erk)
return k
示例3: _worker
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def _worker(self, o):
ct = threading.currentThread()
while 1:
if o is WorkerStop:
break
elif o is not None:
self.working.append(ct)
ctx, function, args, kwargs = o
try:
context.call(ctx, function, *args, **kwargs)
except:
context.call(ctx, log.deferr)
self.working.remove(ct)
del o, ctx, function, args, kwargs
self.waiters.append(ct)
o = self.q.get()
self.waiters.remove(ct)
self.threads.remove(ct)
示例4: reify
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def reify(self):
"""
Determine which objects should receive this event and return a callable
object which will deliver it to them.
Note that this occurs during event propagation, and you probably don't
need to call it directly.
@see: L{iimaginary.IEventObserver.prepare} and
L{TransactionalEventBroadcaster} for a more thorough description of
how this method is used to interact with transactions.
@return: a 0-arg callable object which, when called, will call the
results of all L{IEventObserver}s which were contained within this
L{Event}'s location when this method, L{Event.reify}, was called.
"""
L = []
for observer in (self.location.idea.obtain(
Proximity(0.5, ProviderOf(iimaginary.IEventObserver)))):
sender = observer.prepare(self)
if not callable(sender):
raise TypeError("Senders must be callable", sender)
L.append(sender)
return lambda: map(apply, L)
示例5: runEventTransaction
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def runEventTransaction(store, func, *args, **kwargs):
"""
This takes responsibility for setting up the transactional event
broadcasting junk, handling action errors, and broadcasting commit or
revert events.
"""
broadcaster = TransactionalEventBroadcaster()
def runHelper():
# Set up event context for the duration of the action
# run. Additionally, handle raised ActionFailures by
# adding their events to the revert event list and
# re-raising them so they will revert the transaction.
try:
return context.call(
{iimaginary.ITransactionalEventBroadcaster: broadcaster},
func, *args, **kwargs)
except eimaginary.ActionFailure, e:
broadcaster.addRevertEvent(e.event.reify())
raise
示例6: call
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def call(_, func, *args, **kwargs):
"""Call the given `func`, discarding the first argument.
For example, where ``doSomethingElse`` needs to become part of the
callback chain, is not interested in the result of the previous step, but
which produces an interesting result itself::
d = doSomethingImportant()
d.addCallback(call, doSomethingElse)
d.addCallback(doSomethingWithTheResult)
Often this would be handled by allowing a disposable first argument in
``doSomethingElse``, or with an ugly ``lambda``::
d = doSomethingImportant()
d.addCallback(lambda ignore_this: doSomethingElse())
d.addCallback(doSomethingWithTheResult)
:return: :class:`Deferred`.
"""
return maybeDeferred(func, *args, **kwargs)
示例7: callOut
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def callOut(thing, func, *args, **kwargs):
"""Call out to the given `func`, but return `thing`.
For example::
d = client.fetchSomethingReallyImportant()
d.addCallback(callOut, putKettleOn))
d.addCallback(doSomethingWithReallyImportantThing)
Use this where you need a side-effect when a :py:class:`~Deferred` is
fired, but you don't want to clobber the result. Note that the result
being passed through is *not* passed to the function.
Note also that if the call-out raises an exception, this will be
propagated; nothing is done to suppress the exception or preserve the
result in this case.
:return: :class:`Deferred`.
"""
return maybeDeferred(func, *args, **kwargs).addCallback(lambda _: thing)
示例8: callOutToThread
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def callOutToThread(thing, func, *args, **kwargs):
"""Call out to the given `func` in another thread, but return `thing`.
For example::
d = client.fetchSomethingReallyImportant()
d.addCallback(callOutToThread, watchTheKettleBoil))
d.addCallback(doSomethingWithReallyImportantThing)
Use this where you need a side-effect when a :py:class:`~Deferred` is
fired, but you don't want to clobber the result. Note that the result
being passed through is *not* passed to the function.
Note also that if the call-out raises an exception, this will be
propagated; nothing is done to suppress the exception or preserve the
result in this case.
:return: :class:`Deferred`.
"""
return deferToThread(func, *args, **kwargs).addCallback(lambda _: thing)
示例9: deferToNewThread
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def deferToNewThread(func, *args, **kwargs):
"""Defer `func` into a new thread.
The thread is created for this one function call; it will not have been
previously used, and will not be used again.
:param func: A callable, typically a function.
:param args: A tuple of positional arguments.
:param kwargs: A dict of keyword arguments.
:return: A :class:`Deferred` that fires with the result of `func`.
"""
d = Deferred()
ctx = context.theContextTracker.currentContext().contexts[-1]
thread = threading.Thread(
target=callInThread,
args=(ctx, func, args, kwargs, d),
name="deferToNewThread(%s)" % getattr(func, "__name__", "..."),
)
thread.start()
return d
示例10: wrapFuncInContext
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def wrapFuncInContext(self, func):
"""Return a new function that will call `func` in context."""
# If there's no context defined, return `func` unaltered.
if self.contextFactory is None:
return func
@wraps(func)
def ctxfunc(*args, **kwargs):
with self.contextFactory():
return func(*args, **kwargs)
# For convenience, when introspecting for example, expose the original
# function on the function we're returning.
ctxfunc.func = func
return ctxfunc
示例11: test_returns_Deferred_that_wont_be_cancelled_if_errored
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def test_returns_Deferred_that_wont_be_cancelled_if_errored(self):
clock = self.patch(internet, "reactor", Clock())
# Called without a function argument, `deferWithTimeout` returns a new
# Deferred, and schedules it to be cancelled in `timeout` seconds.
timeout = randint(10, 100)
d = deferWithTimeout(timeout)
[delayed_call] = clock.getDelayedCalls()
# Advance some amount of time to simulate something happening, but
# less than the timeout.
clock.advance(timeout - 1)
# The timeout call is still in place.
self.assertThat(delayed_call, DelayedCallActive)
error = RuntimeError()
d.errback(error)
# After calling d the timeout call has been cancelled.
self.assertThat(delayed_call, DelayedCallCancelled)
# The error has been passed safely on.
self.assertRaises(RuntimeError, extract_result, d)
示例12: test_without_callback_releases_lock_when_underlying_pool_breaks
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def test_without_callback_releases_lock_when_underlying_pool_breaks(self):
pool = self.make_pool() # Limit to a single thread.
exception_type = factory.make_exception_type()
citwc = self.patch_autospec(pool.pool, "callInThreadWithCallback")
citwc.side_effect = exception_type
with TwistedLoggerFixture() as logger:
yield pool.callInThreadWithCallback(None, noop)
# Wait and it shall be released.
yield pool.lock.run(noop)
self.assertThat(pool.lock.tokens, Equals(1))
# An alarming message is logged.
self.assertDocTestMatches(
"""\
Critical failure arranging call in thread
Traceback (most recent call last):
...
maastesting.factory.TestException#...
""",
logger.output,
)
示例13: test_terminates_with_kill_and_killpg
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def test_terminates_with_kill_and_killpg(self):
protocol = SignalPrinterProtocol()
process = yield self.startSignalPrinter(protocol, pgrp=True)
# Capture the pid now; it gets cleared when the process exits.
pid = process.pid
# Terminate and wait for it to exit.
self.terminateSignalPrinter(process, protocol)
yield protocol.done.addErrback(suppress, ProcessTerminated)
# os.kill was called once then os.killpg was called twice because the
# subprocess made itself a process group leader.
self.assertThat(
twisted_module._os_kill,
MockCallsMatch(mock.call(pid, signal.SIGTERM)),
)
self.assertThat(
twisted_module._os_killpg,
MockCallsMatch(
mock.call(pid, signal.SIGQUIT), mock.call(pid, signal.SIGKILL)
),
)
示例14: test_terminates_with_kill_if_not_in_separate_process_group
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def test_terminates_with_kill_if_not_in_separate_process_group(self):
protocol = SignalPrinterProtocol()
process = yield self.startSignalPrinter(protocol, pgrp=False)
# Capture the pid now; it gets cleared when the process exits.
pid = process.pid
# Terminate and wait for it to exit.
self.terminateSignalPrinter(process, protocol)
yield protocol.done.addErrback(suppress, ProcessTerminated)
# os.kill was called 3 times because the subprocess did not make
# itself a process group leader.
self.assertThat(
twisted_module._os_kill,
MockCallsMatch(
mock.call(pid, signal.SIGTERM),
mock.call(pid, signal.SIGQUIT),
mock.call(pid, signal.SIGKILL),
),
)
self.assertThat(twisted_module._os_killpg, MockNotCalled())
示例15: test_get_reader_converts_other_exceptions_to_tftp_error
# 需要导入模块: from twisted.python import context [as 别名]
# 或者: from twisted.python.context import call [as 别名]
def test_get_reader_converts_other_exceptions_to_tftp_error(self):
exception_type = factory.make_exception_type()
exception_message = factory.make_string()
client = Mock()
client.localIdent = factory.make_name("system_id")
client.return_value = fail(exception_type(exception_message))
client_service = Mock()
client_service.getClientNow.return_value = succeed(client)
backend = TFTPBackend(self.make_dir(), client_service)
with TwistedLoggerFixture() as logger:
with ExpectedException(BackendError, re.escape(exception_message)):
yield backend.get_reader(b"pxelinux.cfg/default")
# The original exception is logged.
self.assertDocTestMatches(
"""\
TFTP back-end failed.
Traceback (most recent call last):
...
maastesting.factory.TestException#...
""",
logger.output,
)