Here are the examples of the python api twisted.python.reflect.qual taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
81 Examples
3
Example 1
Project: mythbox Source File: jelly.py
def allowInstancesOf(self, *classes):
"""
SecurityOptions.allowInstances(klass, klass, ...): allow instances
of the specified classes
This will also allow the 'instance', 'class' (renamed 'classobj' in
Python 2.3), and 'module' types, as well as basic types.
"""
self.allowBasicTypes()
self.allowTypes("instance", "class", "classobj", "module")
for klass in classes:
self.allowTypes(qual(klass))
self.allowModules(klass.__module__)
self.allowedClasses[klass] = 1
3
Example 2
def configure(self, filename, storeClass):
"""
Configure the subprocess to examine the file store at the given path
name, with the given dead property storage class.
"""
return self.callRemote(Configure, filename=filename,
appropriateStoreClass=qual(storeClass),
merge=self.service.merge)
3
Example 3
def doIteration(self, delay):
"""
Do one iteration over the readers and writers which have been added.
"""
raise NotImplementedError(
reflect.qual(self.__class__) + " did not implement doIteration")
3
Example 4
Project: mythbox Source File: jelly.py
def getInstanceState(inst, jellier):
"""
Utility method to default to 'normal' state rules in serialization.
"""
if hasattr(inst, "__getstate__"):
state = inst.__getstate__()
else:
state = inst.__dict__
sxp = jellier.prepare(inst)
sxp.extend([qual(inst.__class__), jellier.jelly(state)])
return jellier.preserve(inst, sxp)
3
Example 5
Project: mythbox Source File: _baseprocess.py
def _callProcessExited(self, reason):
default = object()
processExited = getattr(self.proto, 'processExited', default)
if processExited is default:
getWarningMethod()(
_missingProcessExited % (qual(self.proto.__class__),),
DeprecationWarning, stacklevel=0)
else:
processExited(Failure(reason))
3
Example 6
Project: foolscap Source File: copyable.py
def registerCopier(klass, copier):
"""This is a shortcut for arranging to serialize third-party clases.
'copier' must be a callable which accepts an instance of the class you
want to serialize, and returns a tuple of (typename, state_dictionary).
If it returns a typename of None, the original class's fully-qualified
classname is used.
"""
klassname = reflect.qual(klass)
class _CopierAdapter:
implements(ICopyable)
def __init__(self, original):
self.nameToCopy, self.state = copier(original)
if self.nameToCopy is None:
self.nameToCopy = klassname
def getTypeToCopy(self):
return self.nameToCopy
def getStateToCopy(self):
return self.state
registerAdapter(_CopierAdapter, klass, ICopyable)
3
Example 7
def doRead(self):
"""
Called when data is available for reading.
Subclasses must override this method. The result will be interpreted
in the same way as a result of doWrite().
"""
raise NotImplementedError("%s does not implement doRead" %
reflect.qual(self.__class__))
3
Example 8
Project: flumotion Source File: base.py
def perspective_getKeycardClasses(self):
"""
Get the keycard classes the manager's bouncer can authenticate.
@since: 0.3.1
@returns: a deferred, returning a list of keycard class names
@rtype: L{twisted.internet.defer.Deferred} firing list of str
"""
classes = self.vishnu.bouncer.keycardClasses
return [reflect.qual(c) for c in classes]
3
Example 9
def getStateToCopy(self):
"""
Collect state related to the exception which occurred, discarding
state which cannot reasonably be serialized.
"""
state = self.__dict__.copy()
state['tb'] = None
state['frames'] = []
state['stack'] = []
state['value'] = str(self.value) # Exception instance
if isinstance(self.type, str):
state['type'] = self.type
else:
state['type'] = reflect.qual(self.type) # Exception class
if self.unsafeTracebacks:
state['traceback'] = self.getTraceback()
else:
state['traceback'] = 'Traceback unavailable\n'
return state
3
Example 10
def __getstate__(self):
s = failure.Failure.__getstate__(self)
# the ExceptionLikeString we use in self.type is not pickleable, so
# replace it with the same sort of string that we use in the wire
# protocol.
if not isinstance(self.type, str):
s['type'] = reflect.qual(self.type)
return s
3
Example 11
def getTypeToCopy(self):
"""Determine what type tag to send for me.
By default, send the string representation of my class
(package.module.Class); normally this is adequate, but
you may override this to change it.
"""
return reflect.qual(self.__class__)
3
Example 12
def showwarning(self, message, category, filename, lineno, file=None,
line=None):
"""
Twisted-enabled wrapper around L{warnings.showwarning}.
If C{file} is C{None}, the default behaviour is to emit the warning to
the log system, otherwise the original L{warnings.showwarning} Python
function is called.
"""
if file is None:
self.msg(warning=message, category=reflect.qual(category),
filename=filename, lineno=lineno,
format="%(filename)s:%(lineno)s: %(category)s: %(warning)s")
else:
if sys.version_info < (2, 6):
_oldshowwarning(message, category, filename, lineno, file)
else:
_oldshowwarning(message, category, filename, lineno, file, line)
3
Example 13
def doRead(self):
"""Called when data is avaliable for reading.
Subclasses must override this method. The result will be interpreted
in the same way as a result of doWrite().
"""
raise NotImplementedError("%s does not implement doRead" %
reflect.qual(self.__class__))
3
Example 14
Project: mythbox Source File: jelly.py
def _unjelly_class(self, rest):
clist = rest[0].split('.')
modName = '.'.join(clist[:-1])
if not self.taster.isModuleAllowed(modName):
raise InsecureJelly("module %s not allowed" % modName)
klaus = namedObject(rest[0])
objType = type(klaus)
if objType not in (types.ClassType, types.TypeType):
raise InsecureJelly(
"class %r unjellied to something that isn't a class: %r" % (
rest[0], klaus))
if not self.taster.isClassAllowed(klaus):
raise InsecureJelly("class not allowed: %s" % qual(klaus))
return klaus
3
Example 15
def spewer(frame, s, ignored):
"""
A trace function for sys.settrace that prints every function or method call.
"""
from twisted.python import reflect
if frame.f_locals.has_key('self'):
se = frame.f_locals['self']
if hasattr(se, '__class__'):
k = reflect.qual(se.__class__)
else:
k = reflect.qual(type(se))
print 'method %s of %s at %s' % (
frame.f_code.co_name, k, id(se)
)
else:
print 'function %s in %s, line %s' % (
frame.f_code.co_name,
frame.f_code.co_filename,
frame.f_lineno)
3
Example 16
def name(thing):
"""
@param thing: an object from modules (instance of PythonModule,
PythonAttribute), a TestCase subclass, or an instance of a TestCase.
"""
if isTestCase(thing):
# TestCase subclass
theName = reflect.qual(thing)
else:
# thing from trial, or thing from modules.
# this monstrosity exists so that modules' objects do not have to
# implement id(). -jml
try:
theName = thing.id()
except AttributeError:
theName = thing.name
return theName
3
Example 17
def writeSomeData(self, data):
"""
Write as much as possible of the given data, immediately.
This is called to invoke the lower-level writing functionality, such
as a socket's send() method, or a file's write(); this method
returns an integer or an exception. If an integer, it is the number
of bytes written (possibly zero); if an exception, it indicates the
connection was lost.
"""
raise NotImplementedError("%s does not implement writeSomeData" %
reflect.qual(self.__class__))
3
Example 18
def check(self, *errorTypes):
"""Check if this failure's type is in a predetermined list.
@type errorTypes: list of L{Exception} classes or
fully-qualified class names.
@returns: the matching L{Exception} type, or None if no match.
"""
for error in errorTypes:
err = error
if inspect.isclass(error) and issubclass(error, Exception):
err = reflect.qual(error)
if err in self.parents:
return error
return None
3
Example 19
Project: mythbox Source File: test_runner.py
def test_reporterDeprecations(self):
"""
The runner emits a warning if it is using a result that doesn't
implement 'done'.
"""
trialRunner = runner.TrialRunner(None)
result = self.FakeReporter()
trialRunner._makeResult = lambda: result
def f():
# We have to use a pyunit test, otherwise we'll get deprecation
# warnings about using iterate() in a test.
trialRunner.run(pyunit.TestCase('id'))
self.assertWarns(
DeprecationWarning,
"%s should implement done() but doesn't. Falling back to "
"printErrors() and friends." % reflect.qual(result.__class__),
__file__, f)
3
Example 20
Project: ccs-calendarserver Source File: test_migrate.py
@inlineCallbacks
def spawnWithConfig(self, config, here, there):
"""
Similar to spawnWithStore except the child process gets a configuration
object instead.
"""
master = yield self.spawn(AMP(), StoreCreator)
subcfg = copy.deepcopy(self.config)
del subcfg._postUpdateHooks[:]
yield master.callRemote(PickleConfig, config=subcfg,
delegateTo=qual(there))
returnValue(swapAMP(master, here))
3
Example 21
def __repr__(self):
protocolName = reflect.qual(self.protocol.__class__,)
if hasattr(self, 'socket'):
return '<%s on %r>' % (protocolName, self.port)
else:
return '<%s (not listening)>' % (protocolName,)
3
Example 22
def __call__(self, *args, **kw):
import traceback
log.msg('instance method %s.%s' % (reflect.qual(self.my_class), self.name))
log.msg('being called with %r %r' % (args, kw))
traceback.print_stack(file=log.logfile)
assert 0
3
Example 23
def jellyFor(self, jellier):
sxp = jellier.prepare(self)
sxp.extend([
qual(Enum),
self._enumClassName,
self.value, self.name, self.nick])
return jellier.preserve(self, sxp)
3
Example 24
def __getstate__(self, dict=None):
"""Get state, adding a version number to it on its way out.
"""
dct = copy.copy(dict or self.__dict__)
bases = _aybabtu(self.__class__)
bases.reverse()
bases.append(self.__class__) # don't forget me!!
for base in bases:
if base.__dict__.has_key('persistenceForgets'):
for slot in base.persistenceForgets:
if dct.has_key(slot):
del dct[slot]
if base.__dict__.has_key('persistenceVersion'):
dct['%s.persistenceVersion' % reflect.qual(base)] = base.persistenceVersion
return dct
3
Example 25
Project: Piped Source File: providers.py
@defer.inlineCallbacks
def login(self, credentials, mind, *interfaces):
for i in self.checkers:
if i.providedBy(credentials):
for checker in self.checkers[i]:
try:
avatar_id = yield checker.requestAvatarId(credentials)
avatar = yield self.realm.requestAvatar(avatar_id, mind, *interfaces)
defer.returnValue(avatar)
except conch_error.ValidPublicKey:
# This is how SSHPublicKeyDatabase says "Your public key is okay, now prove you have
# the private key to continue".
raise
except error.UnauthorizedLogin:
continue
raise error.UnauthorizedLogin()
ifac = interface.providedBy(credentials)
raise error.UnhandledCredentials("No checker for %s" % ', '.join(map(reflect.qual, ifac)))
3
Example 26
Project: mythbox Source File: util.py
def spewer(frame, s, ignored):
"""A trace function for sys.settrace that prints every function or method call."""
from twisted.python import reflect
if frame.f_locals.has_key('self'):
se = frame.f_locals['self']
if hasattr(se, '__class__'):
k = reflect.qual(se.__class__)
else:
k = reflect.qual(type(se))
print 'method %s of %s at %s' % (
frame.f_code.co_name, k, id(se)
)
else:
print 'function %s in %s, line %s' % (
frame.f_code.co_name,
frame.f_code.co_filename,
frame.f_lineno)
3
Example 27
def __getattr__(self, name):
"""
A getattr method to cause a class to be refreshed.
"""
if name == '__del__':
raise AttributeError("Without this, Python segfaults.")
updateInstance(self)
log.msg("(rebuilding stale %s instance (%s))" % (reflect.qual(self.__class__), name))
result = getattr(self, name)
return result
3
Example 28
def __init__(self, original):
self.original = original
key = reflect.qual(original.__class__)
count = _counters.get(key, 0)
_counters[key] = count + 1
self._logFile = file(key + '-' + str(count), 'w')
3
Example 29
Project: mythbox Source File: jelly.py
def _maybeClass(classnamep):
try:
object
except NameError:
isObject = 0
else:
isObject = isinstance(classnamep, type)
if isinstance(classnamep, ClassType) or isObject:
return qual(classnamep)
return classnamep
3
Example 30
def __getstate__(self, dict=None):
"""Get state, adding a version number to it on its way out.
"""
dct = copy.copy(dict or self.__dict__)
bases = _aybabtu(self.__class__)
bases.reverse()
bases.append(self.__class__) # don't forget me!!
for base in bases:
if 'persistenceForgets' in base.__dict__:
for slot in base.persistenceForgets:
if slot in dct:
del dct[slot]
if 'persistenceVersion' in base.__dict__:
dct['%s.persistenceVersion' % reflect.qual(base)] = base.persistenceVersion
return dct
3
Example 31
def jellyFor(self, jellier):
"""
@see: L{twisted.spread.interfaces.IJellyable.jellyFor}
"""
sxp = jellier.prepare(self)
sxp.extend([
qual(self.__class__),
jellier.jelly(self.getStateFor(jellier))])
return jellier.preserve(self, sxp)
3
Example 32
Project: ccs-calendarserver Source File: test_migrate.py
@inlineCallbacks
def spawnWithStore(self, here, there):
"""
'here' and 'there' are the helper protocols 'there' will expect to be
created with an instance of a store.
"""
master = yield self.spawn(AMP(), StoreCreator)
yield master.callRemote(CreateStore, delegateTo=qual(there))
returnValue(swapAMP(master, here))
3
Example 33
Project: mythbox Source File: jelly.py
def allowTypes(self, *types):
"""
SecurityOptions.allowTypes(typeString): Allow a particular type, by its
name.
"""
for typ in types:
if not isinstance(typ, str):
typ = qual(typ)
self.allowedTypes[typ] = 1
3
Example 34
def __repr__(self):
factoryName = reflect.qual(self.factory.__class__)
if hasattr(self, 'socket'):
return '<%s on %r>' % (factoryName, self.port)
else:
return '<%s (not listening)>' % (factoryName,)
3
Example 35
def __repr__(self):
return ('<%s run=%d errors=%d failures=%d todos=%d dones=%d skips=%d>'
% (reflect.qual(self.__class__), self.testsRun,
len(self.errors), len(self.failures),
len(self.expectedFailures), len(self.skips),
len(self.unexpectedSuccesses)))
3
Example 36
Project: mythbox Source File: sqlreflector.py
def _transPopulateSchema(self):
"""Used to construct the row classes in a single interaction.
"""
for rc in self.rowClasses:
if not issubclass(rc, RowObject):
raise DBError("Stub class (%s) is not derived from RowObject" % reflect.qual(rc.rowClass))
self._populateSchemaFor(rc)
self.populated = 1
3
Example 37
Project: flumotion Source File: portal.py
def getKeycardClasses(self):
"""
Return the Keycard interfaces supported by this portal's bouncer.
@rtype: L{twisted.internet.defer.Deferred} firing list of str
"""
if not self.bouncer:
# no logins will be possible, but we can wait until they try
# to login() to reject them
return []
if hasattr(self.bouncer, 'getKeycardClasses'):
# must return a deferred
return self.bouncer.getKeycardClasses()
else:
interfaces = [reflect.qual(k) for k in self.bouncer.keycardClasses]
return defer.succeed(interfaces)
3
Example 38
def getStateToCopy(self, obj, broker):
state = {}
for k in ('value', 'type', 'parents'):
state[k] = getattr(obj, k)
if broker.unsafeTracebacks:
state['traceback'] = obj.traceback
else:
state['traceback'] = "Traceback unavailable\n"
if not isinstance(state['type'], str):
state['type'] = reflect.qual(state['type']) # Exception class
return state
3
Example 39
Project: mythbox Source File: app.py
def _initialLog(self):
"""
Print twistd start log message.
"""
from twisted.internet import reactor
log.msg("twistd %s (%s %s) starting up." % (copyright.version,
sys.executable,
runtime.shortPythonVersion()))
log.msg('reactor class: %s.' % (qual(reactor.__class__),))
3
Example 40
def render(self, request):
"""
I produce a stream of bytes for the request, by calling request.write()
and request.finish().
"""
raise NotImplementedError("%s.render" % reflect.qual(self.__class__))
0
Example 41
def getTypeToCopy(self):
return reflect.qual(self.__class__)
0
Example 42
Project: mythbox Source File: factory.py
def startFactory(self):
# disable coredumps
if resource:
resource.setrlimit(resource.RLIMIT_CORE, (0,0))
else:
log.msg('INSECURE: unable to disable core dumps.')
if not hasattr(self,'publicKeys'):
self.publicKeys = self.getPublicKeys()
for keyType, value in self.publicKeys.items():
if isinstance(value, str):
warnings.warn("Returning a mapping from strings to "
"strings from getPublicKeys()/publicKeys (in %s) "
"is deprecated. Return a mapping from "
"strings to Key objects instead." %
(qual(self.__class__)),
DeprecationWarning, stacklevel=1)
self.publicKeys[keyType] = keys.Key.fromString(value)
if not hasattr(self,'privateKeys'):
self.privateKeys = self.getPrivateKeys()
for keyType, value in self.privateKeys.items():
if not isinstance(value, keys.Key):
warnings.warn("Returning a mapping from strings to "
"PyCrypto key objects from "
"getPrivateKeys()/privateKeys (in %s) "
"is deprecated. Return a mapping from "
"strings to Key objects instead." %
(qual(self.__class__),),
DeprecationWarning, stacklevel=1)
self.privateKeys[keyType] = keys.Key(value)
if not self.publicKeys or not self.privateKeys:
raise error.ConchError('no host keys, failing')
if not hasattr(self,'primes'):
self.primes = self.getPrimes()
0
Example 43
def __repr__(self):
d = {'class': reflect.qual(self.__class__),
'current': self.current,
'max': self.max}
return '%(class)s(%(max)d, %(current)d)' % d
0
Example 44
Project: mythbox Source File: test_recvline.py
def setUp(self):
# A memory-only terminal emulator, into which the server will
# write things and make other state changes. What ends up
# here is basically what a user would have seen on their
# screen.
testTerminal = NotifyingExpectableBuffer()
# An insults client protocol which will translate bytes
# received from the child process into keystroke commands for
# an ITerminalProtocol.
insultsClient = insults.ClientProtocol(lambda: testTerminal)
# A process protocol which will translate stdout and stderr
# received from the child process to dataReceived calls and
# error reporting on an insults client protocol.
processClient = stdio.TerminalProcessProtocol(insultsClient)
# Run twisted/conch/stdio.py with the name of a class
# implementing ITerminalProtocol. This class will be used to
# handle bytes we send to the child process.
exe = sys.executable
module = stdio.__file__
if module.endswith('.pyc') or module.endswith('.pyo'):
module = module[:-1]
args = [exe, module, reflect.qual(self.serverProtocol)]
env = os.environ.copy()
env["PYTHONPATH"] = os.pathsep.join(sys.path)
from twisted.internet import reactor
clientTransport = reactor.spawnProcess(processClient, exe, args,
env=env, usePTY=True)
self.recvlineClient = self.testTerminal = testTerminal
self.processClient = processClient
self.clientTransport = clientTransport
# Wait for the process protocol and test terminal to become
# connected before proceeding. The former should always
# happen first, but it doesn't hurt to be safe.
return defer.gatherResults(filter(None, [
processClient.onConnection,
testTerminal.expect(">>> ")]))
0
Example 45
Project: mythbox Source File: portal.py
def login(self, credentials, mind, *interfaces):
"""
@param credentials: an implementor of
L{twisted.cred.credentials.ICredentials}
@param mind: an object which implements a client-side interface for
your particular realm. In many cases, this may be None, so if the
word 'mind' confuses you, just ignore it.
@param interfaces: list of interfaces for the perspective that the mind
wishes to attach to. Usually, this will be only one interface, for
example IMailAccount. For highly dynamic protocols, however, this
may be a list like (IMailAccount, IUserChooser, IServiceInfo). To
expand: if we are speaking to the system over IMAP, any information
that will be relayed to the user MUST be returned as an
IMailAccount implementor; IMAP clients would not be able to
understand anything else. Any information about unusual status
would have to be relayed as a single mail message in an
otherwise-empty mailbox. However, in a web-based mail system, or a
PB-based client, the ``mind'' object inside the web server
(implemented with a dynamic page-viewing mechanism such as a
Twisted Web Resource) or on the user's client program may be
intelligent enough to respond to several ``server''-side
interfaces.
@return: A deferred which will fire a tuple of (interface,
avatarAspect, logout). The interface will be one of the interfaces
passed in the 'interfaces' argument. The 'avatarAspect' will
implement that interface. The 'logout' object is a callable which
will detach the mind from the avatar. It must be called when the
user has conceptually disconnected from the service. Although in
some cases this will not be in connectionLost (such as in a
web-based session), it will always be at the end of a user's
interactive session.
"""
for i in self.checkers:
if i.providedBy(credentials):
return maybeDeferred(self.checkers[i].requestAvatarId, credentials
).addCallback(self.realm.requestAvatar, mind, *interfaces
)
ifac = providedBy(credentials)
return defer.fail(failure.Failure(error.UnhandledCredentials(
"No checker for %s" % ', '.join(map(reflect.qual, ifac)))))
0
Example 46
def sliceBody(self, streamable, banana):
yield reflect.qual(self.obj.__class__) # really a second index token
self.obj = getInstanceState(self.obj)
for t in OrderedDictSlicer.sliceBody(self, streamable, banana):
yield t
0
Example 47
def getStateToCopy(self, obj, broker):
#state = obj.__dict__.copy()
#state['tb'] = None
#state['frames'] = []
#state['stack'] = []
state = {}
# string exceptions show up as obj.value == None and
# isinstance(obj.type, str). Normal exceptions show up as obj.value
# == text and obj.type == exception class. We need to make sure we
# can handle both.
if isinstance(obj.value, failure.Failure):
# TODO: how can this happen? I got rid of failure2Copyable, so
# if this case is possible, something needs to replace it
raise RuntimeError("not implemented yet")
#state['value'] = failure2Copyable(obj.value, banana.unsafeTracebacks)
elif isinstance(obj.type, str):
state['value'] = str(obj.value)
state['type'] = obj.type # a string
else:
state['value'] = str(obj.value) # Exception instance
state['type'] = reflect.qual(obj.type) # Exception class
# TODO: I suspect that f.value may be getting a copy of the
# traceback, because I've seen it be 1819 bytes at one point. I had
# assumed that it was just the exception name plus args: whatever
# Exception.__repr__ returns.
state['value'] = truncate(state['value'], 1000)
state['type'] = truncate(state['type'], 200)
if broker.unsafeTracebacks:
if isinstance(obj.type, str):
stack = "getTraceback() not available for string exceptions\n"
else:
stack = obj.getTraceback()
state['traceback'] = stack
# TODO: provide something with globals and locals and HTML and
# all that cool stuff
else:
state['traceback'] = 'Traceback unavailable\n'
# The last few lines are often the most interesting. If we need to
# truncate this, grab the first few lines and then as much of the
# tail as we can get.
if len(state['traceback']) > 1900:
state['traceback'] = (state['traceback'][:700] +
"\n\n-- TRACEBACK ELIDED --\n\n"
+ state['traceback'][-1200:])
parents = obj.parents[:]
if parents:
for i,value in enumerate(parents):
parents[i] = truncate(value, 200)
state['parents'] = parents
return state
0
Example 48
def sliceBody(self, streamable, banana):
yield reflect.qual(self.obj)
0
Example 49
Project: foolscap Source File: test_pb.py
def _testBadMethod2_eb(self, f):
self.failUnlessEqual(reflect.qual(f.type), 'exceptions.AttributeError')
self.failUnlessSubstring("TargetWithoutInterfaces", f.value)
self.failUnlessSubstring(" has no attribute 'remote_missing'", f.value)
0
Example 50
Project: crossbar Source File: cli.py
def run_command_version(options, reactor=None, **kwargs):
"""
Subcommand "crossbar version".
"""
log = make_logger()
# Python
py_ver = '.'.join([str(x) for x in list(sys.version_info[:3])])
py_ver_string = "[%s]" % sys.version.replace('\n', ' ')
if 'pypy_version_info' in sys.__dict__:
py_ver_detail = "{}-{}".format(platform.python_implementation(), '.'.join(str(x) for x in sys.pypy_version_info[:3]))
else:
py_ver_detail = platform.python_implementation()
# Twisted / Reactor
tx_ver = "%s-%s" % (pkg_resources.require("Twisted")[0].version, reactor.__class__.__name__)
tx_loc = "[%s]" % qual(reactor.__class__)
# txaio
txaio_ver = '%s' % pkg_resources.require("txaio")[0].version
# Autobahn
ab_ver = pkg_resources.require("autobahn")[0].version
ab_loc = "[%s]" % qual(WebSocketProtocol)
# UTF8 Validator
s = qual(Utf8Validator)
if 'wsaccel' in s:
utf8_ver = 'wsaccel-%s' % pkg_resources.require('wsaccel')[0].version
elif s.startswith('autobahn'):
utf8_ver = 'autobahn'
else:
# could not detect UTF8 validator type/version
utf8_ver = '?'
utf8_loc = "[%s]" % qual(Utf8Validator)
# XOR Masker
s = qual(XorMaskerNull)
if 'wsaccel' in s:
xor_ver = 'wsaccel-%s' % pkg_resources.require('wsaccel')[0].version
elif s.startswith('autobahn'):
xor_ver = 'autobahn'
else:
# could not detect XOR masker type/version
xor_ver = '?'
xor_loc = "[%s]" % qual(XorMaskerNull)
# JSON Serializer
supported_serializers = ['JSON']
json_ver = 'stdlib'
# MsgPack Serializer
try:
import umsgpack # noqa
msgpack_ver = 'u-msgpack-python-%s' % pkg_resources.require('u-msgpack-python')[0].version
supported_serializers.append('MessagePack')
except ImportError:
msgpack_ver = '-'
# CBOR Serializer
try:
import cbor # noqa
cbor_ver = 'cbor-%s' % pkg_resources.require('cbor')[0].version
supported_serializers.append('CBOR')
except ImportError:
cbor_ver = '-'
# UBJSON Serializer
try:
import ubjson # noqa
ubjson_ver = 'ubjson-%s' % pkg_resources.require('py-ubjson')[0].version
supported_serializers.append('UBJSON')
except ImportError:
ubjson_ver = '-'
# LMDB
try:
import lmdb # noqa
lmdb_lib_ver = '.'.join([str(x) for x in lmdb.version()])
lmdb_ver = '{}/lmdb-{}'.format(pkg_resources.require('lmdb')[0].version, lmdb_lib_ver)
except ImportError:
lmdb_ver = '-'
# Release Public Key
release_pubkey = _read_release_pubkey()
def decorate(text):
return click.style(text, fg='yellow', bold=True)
for line in BANNER.splitlines():
log.info(decorate("{:>40}".format(line)))
pad = " " * 22
log.info(" Crossbar.io : {ver}", ver=decorate(crossbar.__version__))
log.info(" Autobahn : {ver} (with {serializers})", ver=decorate(ab_ver), serializers=', '.join(supported_serializers))
log.trace("{pad}{debuginfo}", pad=pad, debuginfo=decorate(ab_loc))
log.debug(" txaio : {ver}", ver=decorate(txaio_ver))
log.debug(" UTF8 Validator : {ver}", ver=decorate(utf8_ver))
log.trace("{pad}{debuginfo}", pad=pad, debuginfo=decorate(utf8_loc))
log.debug(" XOR Masker : {ver}", ver=decorate(xor_ver))
log.trace("{pad}{debuginfo}", pad=pad, debuginfo=decorate(xor_loc))
log.debug(" JSON Codec : {ver}", ver=decorate(json_ver))
log.debug(" MessagePack Codec : {ver}", ver=decorate(msgpack_ver))
log.debug(" CBOR Codec : {ver}", ver=decorate(cbor_ver))
log.debug(" UBJSON Codec : {ver}", ver=decorate(ubjson_ver))
log.info(" Twisted : {ver}", ver=decorate(tx_ver))
log.trace("{pad}{debuginfo}", pad=pad, debuginfo=decorate(tx_loc))
log.info(" LMDB : {ver}", ver=decorate(lmdb_ver))
log.info(" Python : {ver}/{impl}", ver=decorate(py_ver), impl=decorate(py_ver_detail))
log.trace("{pad}{debuginfo}", pad=pad, debuginfo=decorate(py_ver_string))
log.info(" OS : {ver}", ver=decorate(platform.platform()))
log.info(" Machine : {ver}", ver=decorate(platform.machine()))
log.info(" Release key : {release_pubkey}", release_pubkey=decorate(release_pubkey[u'base64']))
log.info("")