Here are the examples of the python api twisted.python.reflect.safe_repr taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
20 Examples
3
Example 1
def __repr__(self):
if hasattr(self.f, 'func_name'):
func = self.f.func_name
if hasattr(self.f, 'im_class'):
func = self.f.im_class.__name__ + '.' + func
else:
func = reflect.safe_repr(self.f)
return 'LoopingCall<%r>(%s, *%s, **%s)' % (
self.interval, func, reflect.safe_repr(self.a),
reflect.safe_repr(self.kw))
3
Example 2
def test_workingRepr(self):
"""
L{reflect.safe_repr} produces the same output as C{repr} on a working
object.
"""
x = [1, 2, 3]
self.assertEquals(reflect.safe_repr(x), repr(x))
3
Example 3
def test_brokenRepr(self):
"""
L{reflect.safe_repr} returns a string with class name, address, and
traceback when the repr call failed.
"""
b = Breakable()
b.breakRepr = True
bRepr = reflect.safe_repr(b)
self.assertIn("Breakable instance at 0x", bRepr)
# Check that the file is in the repr, but without the extension as it
# can be .py/.pyc
self.assertIn(os.path.splitext(__file__)[0], bRepr)
self.assertIn("RuntimeError: repr!", bRepr)
3
Example 4
def test_brokenStr(self):
"""
L{reflect.safe_repr} isn't affected by a broken C{__str__} method.
"""
b = Breakable()
b.breakStr = True
self.assertEquals(reflect.safe_repr(b), repr(b))
3
Example 5
def test_unsignedID(self):
"""
L{unsignedID} is used to print ID of the object in case of error, not
standard ID value which can be negative.
"""
class X(BTBase):
breakRepr = True
ids = {X: 100}
def fakeID(obj):
try:
return ids[obj]
except (TypeError, KeyError):
return id(obj)
self.addCleanup(util.setIDFunction, util.setIDFunction(fakeID))
xRepr = reflect.safe_repr(X)
self.assertIn("0x64", xRepr)
3
Example 6
def test_brokenClassAttribute(self):
"""
If an object raises an exception when accessing its C{__class__}
attribute, L{reflect.safe_repr} uses C{type} to retrieve the class
object.
"""
b = NoClassAttr()
b.breakRepr = True
bRepr = reflect.safe_repr(b)
self.assertIn("NoClassAttr instance at 0x", bRepr)
self.assertIn(os.path.splitext(__file__)[0], bRepr)
self.assertIn("RuntimeError: repr!", bRepr)
3
Example 7
def test_brokenClassNameAttribute(self):
"""
If a class raises an exception when accessing its C{__name__} attribute
B{and} when calling its C{__str__} implementation, L{reflect.safe_repr}
returns 'BROKEN CLASS' instead of the class name.
"""
class X(BTBase):
breakName = True
xRepr = reflect.safe_repr(X())
self.assertIn("<BROKEN CLASS AT 0x", xRepr)
self.assertIn(os.path.splitext(__file__)[0], xRepr)
self.assertIn("RuntimeError: repr!", xRepr)
3
Example 8
def __repr__(self):
if hasattr(self.f, '__qualname__'):
func = self.f.__qualname__
elif hasattr(self.f, '__name__'):
func = self.f.__name__
if hasattr(self.f, 'im_class'):
func = self.f.im_class.__name__ + '.' + func
else:
func = reflect.safe_repr(self.f)
return 'LoopingCall<%r>(%s, *%s, **%s)' % (
self.interval, func, reflect.safe_repr(self.a),
reflect.safe_repr(self.kw))
3
Example 9
Project: TwistedBot Source File: failure.py
def _safeReprVars(varsDictItems):
"""
Convert a list of (name, object) pairs into (name, repr) pairs.
L{twisted.python.reflect.safe_repr} is used to generate the repr, so no
exceptions will be raised by faulty C{__repr__} methods.
@param varsDictItems: a sequence of (name, value) pairs as returned by e.g.
C{locals().items()}.
@returns: a sequence of (name, repr) pairs.
"""
return [(name, reflect.safe_repr(obj)) for (name, obj) in varsDictItems]
3
Example 10
def test_workingRepr(self):
"""
L{reflect.safe_repr} produces the same output as C{repr} on a working
object.
"""
x = [1, 2, 3]
self.assertEqual(reflect.safe_repr(x), repr(x))
3
Example 11
def test_brokenStr(self):
"""
L{reflect.safe_repr} isn't affected by a broken C{__str__} method.
"""
b = Breakable()
b.breakStr = True
self.assertEqual(reflect.safe_repr(b), repr(b))
0
Example 12
Project: flumotion Source File: rtsp.py
def _renderCallback(self, result, resrc):
body = result
if type(body) is not types.StringType:
self.warning('request did not return a string but %r' %
type(body))
body = self._error(INTERNAL_SERVER_ERROR,
"Request did not return a string",
"Request: " + reflect.safe_repr(self),
"Resource: " + reflect.safe_repr(resrc),
"Value: " + reflect.safe_repr(body))
self.setHeader('Content-Length', str(len(body)))
lines = []
for key, value in self.headers.items():
lines.append("%s: %s" % (key, value))
# FIXME: debug response code
self.debug('responding to %s %s with %s (%d)' % (
self.method, self.path, self.code_message, self.code))
self.debug('outgoing headers:\n%s\n' % "\n".join(lines))
if body:
self.debug('body:\n%s\n' % body)
self.log('RTSPRequest._renderCallback(): outgoing response:\n%s\n' %
"\n".join(lines))
self.log("\n".join(lines))
self.log("\n")
self.log(body)
self.channel.site.logReply(self.code, self.code_message, lines, body)
self.write(body)
self.finish()
0
Example 13
def __str__(self):
if self._str is not None:
return self._str
if hasattr(self, 'func'):
if hasattr(self.func, 'func_name'):
func = self.func.func_name
if hasattr(self.func, 'im_class'):
func = self.func.im_class.__name__ + '.' + func
else:
func = reflect.safe_repr(self.func)
else:
func = None
now = self.seconds()
L = ['<DelayedCall 0x%x [%ss] called=%s cancelled=%s' %
(util.unsignedID(self), self.time - now, self.called, self.cancelled)]
if func is not None:
L.extend((' ', func, '('))
if self.a:
L.append(', '.join([reflect.safe_repr(e) for e in self.a]))
if self.kw:
L.append(', ')
if self.kw:
L.append(', '.join(['%s=%s' % (k, reflect.safe_repr(v)) for (k, v) in self.kw.iteritems()]))
L.append(')')
if self.debug:
L.append('\n\ntraceback at creation: \n\n%s' % (' '.join(self.creator)))
L.append('>')
return ''.join(L)
0
Example 14
def __str__(self):
if self._str is not None:
return self._str
if hasattr(self, 'func'):
if hasattr(self.func, 'func_name'):
func = self.func.func_name
if hasattr(self.func, 'im_class'):
func = self.func.im_class.__name__ + '.' + func
else:
func = reflect.safe_repr(self.func)
else:
func = None
now = self.seconds()
L = ["<DelayedCall 0x%x [%ss] called=%s cancelled=%s" % (
unsignedID(self), self.time - now, self.called,
self.cancelled)]
if func is not None:
L.extend((" ", func, "("))
if self.args:
L.append(", ".join([reflect.safe_repr(e) for e in self.args]))
if self.kw:
L.append(", ")
if self.kw:
L.append(", ".join(['%s=%s' % (k, reflect.safe_repr(v)) for (k, v) in self.kw.iteritems()]))
L.append(")")
if self.debug:
L.append("\n\ntraceback at creation: \n\n%s" % (' '.join(self.creator)))
L.append('>')
return "".join(L)
0
Example 15
def __getstate__(self):
"""Avoid pickling objects in the traceback.
"""
if self.pickled:
return self.__dict__
c = self.__dict__.copy()
c['frames'] = [
[
v[0], v[1], v[2],
[(j[0], reflect.safe_repr(j[1])) for j in v[3]],
[(j[0], reflect.safe_repr(j[1])) for j in v[4]]
] for v in self.frames
]
# added 2003-06-23. See comment above in __init__
c['tb'] = None
if self.stack is not None:
# XXX: This is a band-aid. I can't figure out where these
# (failure.stack is None) instances are coming from.
c['stack'] = [
[
v[0], v[1], v[2],
[(j[0], reflect.safe_repr(j[1])) for j in v[3]],
[(j[0], reflect.safe_repr(j[1])) for j in v[4]]
] for v in self.stack
]
c['pickled'] = 1
return c
0
Example 16
def test_brokenClassRepr(self):
class X(BTBase):
breakRepr = True
reflect.safe_repr(X)
reflect.safe_repr(X())
0
Example 17
def test_brokenClassStr(self):
class X(BTBase):
breakStr = True
reflect.safe_repr(X)
reflect.safe_repr(X())
0
Example 18
Project: Firefly Source File: delayrequest.py
def render(self, resrc):
"""
Ask a resource to render itself.
@param resrc: a L{twisted.web.resource.IResource}.
"""
try:
body = resrc.render(self)
except UnsupportedMethod, e:
allowedMethods = e.allowedMethods
if (self.method == "HEAD") and ("GET" in allowedMethods):
# We must support HEAD (RFC 2616, 5.1.1). If the
# resource doesn't, fake it by giving the resource
# a 'GET' request and then return only the headers,
# not the body.
log.msg("Using GET to fake a HEAD request for %s" %
(resrc,))
self.method = "GET"
self._inFakeHead = True
body = resrc.render(self)
if body is NOT_DONE_YET:
log.msg("Tried to fake a HEAD request for %s, but "
"it got away from me." % resrc)
# Oh well, I guess we won't include the content length.
else:
self.setHeader('content-length', str(len(body)))
self._inFakeHead = False
self.method = "HEAD"
self.write('')
self.finish()
return
if self.method in (supportedMethods):
# We MUST include an Allow header
# (RFC 2616, 10.4.6 and 14.7)
self.setHeader('Allow', ', '.join(allowedMethods))
s = ('''Your browser approached me (at %(URI)s) with'''
''' the method "%(method)s". I only allow'''
''' the method%(plural)s %(allowed)s here.''' % {
'URI': escape(self.uri),
'method': self.method,
'plural': ((len(allowedMethods) > 1) and 's') or '',
'allowed': string.join(allowedMethods, ', ')
})
epage = resource.ErrorPage(http.NOT_ALLOWED,
"Method Not Allowed", s)
body = epage.render(self)
else:
epage = resource.ErrorPage(
http.NOT_IMPLEMENTED, "Huh?",
"I don't know how to treat a %s request." %
(escape(self.method),))
body = epage.render(self)
# end except UnsupportedMethod
if body == NOT_DONE_YET:
return
if not isinstance(body, defer.Deferred) and type(body) is not types.StringType:
body = resource.ErrorPage(
http.INTERNAL_SERVER_ERROR,
"Request did not return a string",
"Request: " + html.PRE(reflect.safe_repr(self)) + "<br />" +
"Resource: " + html.PRE(reflect.safe_repr(resrc)) + "<br />" +
"Value: " + html.PRE(reflect.safe_repr(body))).render(self)
if self.method == "HEAD":
if len(body) > 0:
# This is a Bad Thing (RFC 2616, 9.4)
log.msg("Warning: HEAD request %s for resource %s is"
" returning a message body."
" I think I'll eat it."
% (self, resrc))
self.setHeader('content-length', str(len(body)))
self.write('')
self.finish()
else:
if isinstance(body, defer.Deferred):
body.addCallback(self._deferwrite)
else:
self.setHeader('content-length', str(len(body)))
self.write(body)
self.finish()
0
Example 19
def __str__(self):
if self._str is not None:
return self._str
if hasattr(self, 'func'):
# This code should be replaced by a utility function in reflect;
# see ticket #6066:
if hasattr(self.func, '__qualname__'):
func = self.func.__qualname__
elif hasattr(self.func, '__name__'):
func = self.func.func_name
if hasattr(self.func, 'im_class'):
func = self.func.im_class.__name__ + '.' + func
else:
func = reflect.safe_repr(self.func)
else:
func = None
now = self.seconds()
L = ["<DelayedCall 0x%x [%ss] called=%s cancelled=%s" % (
unsignedID(self), self.time - now, self.called,
self.cancelled)]
if func is not None:
L.extend((" ", func, "("))
if self.args:
L.append(", ".join([reflect.safe_repr(e) for e in self.args]))
if self.kw:
L.append(", ")
if self.kw:
L.append(", ".join(['%s=%s' % (k, reflect.safe_repr(v)) for (k, v) in self.kw.items()]))
L.append(")")
if self.debug:
L.append("\n\ntraceback at creation: \n\n%s" % (' '.join(self.creator)))
L.append('>')
return "".join(L)
0
Example 20
Project: SubliminalCollaborator Source File: server.py
def render(self, resrc):
"""
Ask a resource to render itself.
@param resrc: a L{twisted.web.resource.IResource}.
"""
try:
body = resrc.render(self)
except UnsupportedMethod, e:
allowedMethods = e.allowedMethods
if (self.method == "HEAD") and ("GET" in allowedMethods):
# We must support HEAD (RFC 2616, 5.1.1). If the
# resource doesn't, fake it by giving the resource
# a 'GET' request and then return only the headers,
# not the body.
log.msg("Using GET to fake a HEAD request for %s" %
(resrc,))
self.method = "GET"
self._inFakeHead = True
body = resrc.render(self)
if body is NOT_DONE_YET:
log.msg("Tried to fake a HEAD request for %s, but "
"it got away from me." % resrc)
# Oh well, I guess we won't include the content length.
else:
self.setHeader('content-length', str(len(body)))
self._inFakeHead = False
self.method = "HEAD"
self.write('')
self.finish()
return
if self.method in (supportedMethods):
# We MUST include an Allow header
# (RFC 2616, 10.4.6 and 14.7)
self.setHeader('Allow', ', '.join(allowedMethods))
s = ('''Your browser approached me (at %(URI)s) with'''
''' the method "%(method)s". I only allow'''
''' the method%(plural)s %(allowed)s here.''' % {
'URI': escape(self.uri),
'method': self.method,
'plural': ((len(allowedMethods) > 1) and 's') or '',
'allowed': string.join(allowedMethods, ', ')
})
epage = resource.ErrorPage(http.NOT_ALLOWED,
"Method Not Allowed", s)
body = epage.render(self)
else:
epage = resource.ErrorPage(
http.NOT_IMPLEMENTED, "Huh?",
"I don't know how to treat a %s request." %
(escape(self.method),))
body = epage.render(self)
# end except UnsupportedMethod
if body == NOT_DONE_YET:
return
if type(body) is not types.StringType:
body = resource.ErrorPage(
http.INTERNAL_SERVER_ERROR,
"Request did not return a string",
"Request: " + html.PRE(reflect.safe_repr(self)) + "<br />" +
"Resource: " + html.PRE(reflect.safe_repr(resrc)) + "<br />" +
"Value: " + html.PRE(reflect.safe_repr(body))).render(self)
if self.method == "HEAD":
if len(body) > 0:
# This is a Bad Thing (RFC 2616, 9.4)
log.msg("Warning: HEAD request %s for resource %s is"
" returning a message body."
" I think I'll eat it."
% (self, resrc))
self.setHeader('content-length', str(len(body)))
self.write('')
else:
self.setHeader('content-length', str(len(body)))
self.write(body)
self.finish()