本文整理匯總了Python中twisted.python.context.get方法的典型用法代碼示例。如果您正苦於以下問題:Python context.get方法的具體用法?Python context.get怎麽用?Python context.get使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類twisted.python.context
的用法示例。
在下文中一共展示了context.get方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: observe
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def observe(self, event):
if event.get("type") == "operation":
event = event.copy()
lag = event.get('lag')
if lag is None:
event['lag'] = ''
else:
event['lag'] = self.lagFormat % (lag * 1000.0,)
self._outfile.write(
(self.formats[event[u'phase']] % event).encode('utf-8') + '\n')
if event[u'phase'] == u'end':
dataset = self._perOperationTimes.setdefault(event[u'label'], [])
dataset.append((event[u'success'], event[u'duration']))
elif lag is not None:
dataset = self._perOperationLags.setdefault(event[u'label'], [])
dataset.append(lag)
示例2: test_calls_given_function_and_always_returns_Deferred
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_calls_given_function_and_always_returns_Deferred(self):
clock = self.patch(internet, "reactor", Clock())
def do_something(a, *b, **c):
return do_something, a, b, c
# Any given function is called via `maybeDeferred`. In this case, we
# get an already-called Deferred, because `do_something` is
# synchronous.
timeout = randint(10, 100)
d = deferWithTimeout(
timeout, do_something, sentinel.a, sentinel.b, c=sentinel.c
)
self.assertThat(d, IsInstance(Deferred))
self.assertEqual(
(do_something, sentinel.a, (sentinel.b,), {"c": sentinel.c}),
extract_result(d),
)
# The timeout has already been cancelled.
self.assertThat(clock.getDelayedCalls(), Equals([]))
示例3: test_logPrefix
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_logPrefix(self):
"""
Client and server transports implement L{ILoggingContext.logPrefix} to
return a message reflecting the protocol they are running.
"""
class CustomLogPrefixProtocol(ConnectableProtocol):
def __init__(self, prefix):
self._prefix = prefix
self.system = None
def connectionMade(self):
self.transport.write(b"a")
def logPrefix(self):
return self._prefix
def dataReceived(self, bytes):
self.system = context.get(ILogContext)["system"]
self.transport.write(b"b")
# Only close connection if both sides have received data, so
# that both sides have system set.
if b"b" in bytes:
self.transport.loseConnection()
client = CustomLogPrefixProtocol("Custom Client")
server = CustomLogPrefixProtocol("Custom Server")
runProtocolsWithReactor(self, server, client, self.endpoints)
self.assertIn("Custom Client", client.system)
self.assertIn("Custom Server", server.system)
示例4: test_protocolGarbageAfterLostConnection
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_protocolGarbageAfterLostConnection(self):
"""
After the connection a protocol is being used for is closed, the
reactor discards all of its references to the protocol.
"""
lostConnectionDeferred = Deferred()
clientProtocol = ClosingLaterProtocol(lostConnectionDeferred)
clientRef = ref(clientProtocol)
reactor = self.buildReactor()
portDeferred = self.endpoints.server(reactor).listen(
ServerFactory.forProtocol(Protocol))
def listening(port):
msg("Listening on %r" % (port.getHost(),))
endpoint = self.endpoints.client(reactor, port.getHost())
client = endpoint.connect(
ClientFactory.forProtocol(lambda: clientProtocol))
def disconnect(proto):
msg("About to disconnect %r" % (proto,))
proto.transport.loseConnection()
client.addCallback(disconnect)
client.addErrback(lostConnectionDeferred.errback)
return lostConnectionDeferred
def onListening():
portDeferred.addCallback(listening)
portDeferred.addErrback(err)
portDeferred.addBoth(lambda ignored: reactor.stop())
needsRunningReactor(reactor, onListening)
self.runReactor(reactor)
# Drop the reference and get the garbage collector to tell us if there
# are no references to the protocol instance left in the reactor.
clientProtocol = None
collect()
self.assertIsNone(clientRef())
示例5: test_connectEvent
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_connectEvent(self):
"""
This test checks that we correctly get notifications event for a
client. This ought to prevent a regression under Windows using the
GTK2 reactor. See #3925.
"""
reactor = self.buildReactor()
self.listen(reactor, ServerFactory.forProtocol(Protocol))
connected = []
class CheckConnection(Protocol):
def connectionMade(self):
connected.append(self)
reactor.stop()
clientFactory = Stop(reactor)
clientFactory.protocol = CheckConnection
needsRunningReactor(
reactor, lambda: self.connect(reactor, clientFactory))
reactor.run()
self.assertTrue(connected)
示例6: test_logPrefix
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_logPrefix(self):
"""
Datagram transports implement L{ILoggingContext.logPrefix} to return a
message reflecting the protocol they are running.
"""
class CustomLogPrefixDatagramProtocol(DatagramProtocol):
def __init__(self, prefix):
self._prefix = prefix
self.system = Deferred()
def logPrefix(self):
return self._prefix
def datagramReceived(self, bytes, addr):
if self.system is not None:
system = self.system
self.system = None
system.callback(context.get(ILogContext)["system"])
reactor = self.buildReactor()
protocol = CustomLogPrefixDatagramProtocol("Custom Datagrams")
d = protocol.system
port = self.getListeningPort(reactor, protocol)
address = port.getHost()
def gotSystem(system):
self.assertEqual("Custom Datagrams (UDP)", system)
d.addCallback(gotSystem)
d.addErrback(err)
d.addCallback(lambda ignored: reactor.stop())
port.write(b"some bytes", ('127.0.0.1', address.port))
self.runReactor(reactor)
示例7: msg
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def msg(self, *message, **kw):
"""
Log a new message.
The message should be a native string, i.e. bytes on Python 2 and
Unicode on Python 3. For compatibility with both use the native string
syntax, for example::
>>> log.msg('Hello, world.')
You MUST avoid passing in Unicode on Python 2, and the form::
>>> log.msg('Hello ', 'world.')
This form only works (sometimes) by accident.
Keyword arguments will be converted into items in the event
dict that is passed to L{ILogObserver} implementations.
Each implementation, in turn, can define keys that are used
by it specifically, in addition to common keys listed at
L{ILogObserver.__call__}.
For example, to set the C{system} parameter while logging
a message::
>>> log.msg('Started', system='Foo')
"""
actualEventDict = (context.get(ILogContext) or {}).copy()
actualEventDict.update(kw)
actualEventDict['message'] = message
actualEventDict['time'] = time.time()
if "isError" not in actualEventDict:
actualEventDict["isError"] = 0
_publishNew(self._publishPublisher, actualEventDict, textFromEventDict)
示例8: textFromEventDict
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def textFromEventDict(eventDict):
"""
Extract text from an event dict passed to a log observer. If it cannot
handle the dict, it returns None.
The possible keys of eventDict are:
- C{message}: by default, it holds the final text. It's required, but can
be empty if either C{isError} or C{format} is provided (the first
having the priority).
- C{isError}: boolean indicating the nature of the event.
- C{failure}: L{failure.Failure} instance, required if the event is an
error.
- C{why}: if defined, used as header of the traceback in case of errors.
- C{format}: string format used in place of C{message} to customize
the event. It uses all keys present in C{eventDict} to format
the text.
Other keys will be used when applying the C{format}, or ignored.
"""
edm = eventDict['message']
if not edm:
if eventDict['isError'] and 'failure' in eventDict:
why = eventDict.get('why')
if why:
why = reflect.safe_str(why)
else:
why = 'Unhandled Error'
try:
traceback = eventDict['failure'].getTraceback()
except Exception as e:
traceback = '(unable to obtain traceback): ' + str(e)
text = (why + '\n' + traceback)
elif 'format' in eventDict:
text = _safeFormat(eventDict['format'], eventDict)
else:
# We don't know how to log this
return None
else:
text = ' '.join(map(reflect.safe_str, edm))
return text
示例9: installContextTracker
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def installContextTracker(ctr):
global theContextTracker
global call
global get
theContextTracker = ctr
call = theContextTracker.callWithContext
get = theContextTracker.getContext
示例10: test_doDoesWorkInWorker
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_doDoesWorkInWorker(self):
"""
L{Team.do} does the work in a worker created by the createWorker
callable.
"""
def something():
something.who = get("worker")
self.team.do(something)
self.coordinate()
self.assertEqual(self.team.statistics().busyWorkerCount, 1)
self.performAllOutstandingWork()
self.assertEqual(something.who, 1)
self.assertEqual(self.team.statistics().busyWorkerCount, 0)
示例11: test_stringPythonLogLevel
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_stringPythonLogLevel(self):
"""
If a stdlib log level was provided as a string (eg. C{"WARNING"}) in
the legacy "logLevel" key, it does not get converted to a number.
The documentation suggested that numerical values should be used but
this was not a requirement.
"""
event = self.forwardAndVerify(dict(
logLevel="WARNING", # py_logging.WARNING is 30
))
self.assertEqual(event["logLevel"], "WARNING")
示例12: test_isError
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_isError(self):
"""
If C{"isError"} is set to C{1} (true) on the legacy event, the
C{"log_level"} key should get set to L{LogLevel.critical}.
"""
publishToNewObserver(
self.observer,
self.legacyEvent(isError=1),
legacyLog.textFromEventDict
)
self.assertEqual(self.events[0]["log_level"], LogLevel.critical)
示例13: test_stdlibLogLevel
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_stdlibLogLevel(self):
"""
If the old-style C{"logLevel"} key is set to a standard library logging
level, using a predefined (L{int}) constant, the new-style
C{"log_level"} key should get set to the corresponding log level.
"""
publishToNewObserver(
self.observer,
self.legacyEvent(logLevel=py_logging.WARNING),
legacyLog.textFromEventDict
)
self.assertEqual(self.events[0]["log_level"], LogLevel.warn)
示例14: test_stdlibLogLevelWithString
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_stdlibLogLevelWithString(self):
"""
If the old-style C{"logLevel"} key is set to a standard library logging
level, using a string value, the new-style C{"log_level"} key should
get set to the corresponding log level.
"""
publishToNewObserver(
self.observer,
self.legacyEvent(logLevel="WARNING"),
legacyLog.textFromEventDict
)
self.assertEqual(self.events[0]["log_level"], LogLevel.warn)
示例15: test_stdlibLogLevelWithGarbage
# 需要導入模塊: from twisted.python import context [as 別名]
# 或者: from twisted.python.context import get [as 別名]
def test_stdlibLogLevelWithGarbage(self):
"""
If the old-style C{"logLevel"} key is set to a standard library logging
level, using an unknown value, the new-style C{"log_level"} key should
not get set.
"""
publishToNewObserver(
self.observer,
self.legacyEvent(logLevel="Foo!!!!!"),
legacyLog.textFromEventDict
)
self.assertNotIn("log_level", self.events[0])