Python twisted.python.reflect.safe_str() Examples
The following are 30
code examples of twisted.python.reflect.safe_str().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
twisted.python.reflect
, or try the search function
.
Example #1
Source File: outbound.py From magic-wormhole with MIT License | 6 votes |
def _pull(self): while True: try: self._producer.resumeProducing() except Exception: log.err(None, "%s failed, producing will be stopped:" % (safe_str(self._producer),)) try: self._unregister() # The consumer should now call stopStreaming() on us, # thus stopping the streaming. except Exception: # Since the consumer blew up, we may not have had # stopStreaming() called, so we just stop on our own: log.err(None, "%s failed to unregister producer:" % (safe_str(self._unregister),)) self._finished = True return yield None
Example #2
Source File: log.py From BitTorrent with GNU General Public License v3.0 | 6 votes |
def emit(self, eventDict): edm = eventDict['message'] if not edm: if eventDict['isError'] and eventDict.has_key('failure'): text = eventDict['failure'].getTraceback() elif eventDict.has_key('format'): text = self._safeFormat(eventDict['format'], eventDict) else: # we don't know how to log this return else: text = ' '.join(map(reflect.safe_str, edm)) timeStr = time.strftime(self.timeFormat, time.localtime(eventDict['time'])) fmtDict = {'system': eventDict['system'], 'text': text.replace("\n", "\n\t")} msgStr = self._safeFormat("[%(system)s] %(text)s\n", fmtDict) util.untilConcludes(self.write, timeStr + " " + msgStr) util.untilConcludes(self.flush) # Hoorj!
Example #3
Source File: test_reflect.py From python-for-android with Apache License 2.0 | 5 votes |
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_str} returns 'BROKEN CLASS' instead of the class name. """ class X(BTBase): breakName = True xStr = reflect.safe_str(X()) self.assertIn("<BROKEN CLASS AT 0x", xStr) self.assertIn(os.path.splitext(__file__)[0], xStr) self.assertIn("RuntimeError: str!", xStr)
Example #4
Source File: _producer_helpers.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def _pull(self): """ A generator that calls C{resumeProducing} on the underlying producer forever. If C{resumeProducing} throws an exception, the producer is unregistered, which should result in streaming stopping. """ while True: try: self._producer.resumeProducing() except: log.err(None, "%s failed, producing will be stopped:" % (safe_str(self._producer),)) try: self._consumer.unregisterProducer() # The consumer should now call stopStreaming() on us, # thus stopping the streaming. except: # Since the consumer blew up, we may not have had # stopStreaming() called, so we just stop on our own: log.err(None, "%s failed to unregister producer:" % (safe_str(self._consumer),)) self._finished = True return yield None
Example #5
Source File: test_reflect.py From learn_python3_spider with MIT License | 5 votes |
def test_brokenClassAttribute(self): """ If an object raises an exception when accessing its C{__class__} attribute, L{reflect.safe_str} uses C{type} to retrieve the class object. """ b = NoClassAttr() b.breakStr = True bStr = reflect.safe_str(b) self.assertIn("NoClassAttr instance at 0x", bStr) self.assertIn(os.path.splitext(__file__)[0], bStr) self.assertIn("RuntimeError: str!", bStr)
Example #6
Source File: test_reflect.py From learn_python3_spider with MIT License | 5 votes |
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_str} returns 'BROKEN CLASS' instead of the class name. """ class X(BTBase): breakName = True xStr = reflect.safe_str(X()) self.assertIn("<BROKEN CLASS AT 0x", xStr) self.assertIn(os.path.splitext(__file__)[0], xStr) self.assertIn("RuntimeError: str!", xStr)
Example #7
Source File: log.py From python-for-android with Apache License 2.0 | 5 votes |
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: text = ((eventDict.get('why') or 'Unhandled Error') + '\n' + eventDict['failure'].getTraceback()) elif 'format' in eventDict: text = _safeFormat(eventDict['format'], eventDict) else: # we don't know how to log this return else: text = ' '.join(map(reflect.safe_str, edm)) return text
Example #8
Source File: failure.py From python-for-android with Apache License 2.0 | 5 votes |
def getErrorMessage(self): """Get a string of the exception which caused this Failure.""" if isinstance(self.value, Failure): return self.value.getErrorMessage() return reflect.safe_str(self.value)
Example #9
Source File: test_reflect.py From python-for-android with Apache License 2.0 | 5 votes |
def test_workingStr(self): x = [1, 2, 3] self.assertEquals(reflect.safe_str(x), str(x))
Example #10
Source File: test_reflect.py From python-for-android with Apache License 2.0 | 5 votes |
def test_brokenStr(self): b = Breakable() b.breakStr = True reflect.safe_str(b)
Example #11
Source File: test_reflect.py From python-for-android with Apache License 2.0 | 5 votes |
def test_brokenRepr(self): b = Breakable() b.breakRepr = True reflect.safe_str(b)
Example #12
Source File: test_reflect.py From python-for-android with Apache License 2.0 | 5 votes |
def test_brokenClassRepr(self): class X(BTBase): breakRepr = True reflect.safe_str(X) reflect.safe_str(X())
Example #13
Source File: test_reflect.py From python-for-android with Apache License 2.0 | 5 votes |
def test_brokenClassAttribute(self): """ If an object raises an exception when accessing its C{__class__} attribute, L{reflect.safe_str} uses C{type} to retrieve the class object. """ b = NoClassAttr() b.breakStr = True bStr = reflect.safe_str(b) self.assertIn("NoClassAttr instance at 0x", bStr) self.assertIn(os.path.splitext(__file__)[0], bStr) self.assertIn("RuntimeError: str!", bStr)
Example #14
Source File: test_reflect.py From learn_python3_spider with MIT License | 5 votes |
def test_brokenClassStr(self): class X(BTBase): breakStr = True reflect.safe_str(X) reflect.safe_str(X())
Example #15
Source File: twisted_logger.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def emit(self, eventDict): system = eventDict['system'] if system == '-': system = 'twisted' else: system = 'twisted.' + system logger = logging.getLogger(system) # This next line is obnoxious. --Dave #logger.setLevel(logging.DEBUG) edm = eventDict['message'] or '' if eventDict['isError'] and eventDict.has_key('failure'): if not edm: edm = 'Failure:' logger.log(self.error_log_level, edm, exc_info=eventDict['failure'].exc_info()) elif eventDict.has_key('format'): try: text = self._safeFormat(eventDict['format'], eventDict) except: try: text = eventDict['format']%eventDict; except: text = repr(eventDict); logger.log(self.info_log_level, text) else: text = ' '.join(map(reflect.safe_str, edm)) logger.log(self.info_log_level, text)
Example #16
Source File: twisted_logger.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def emit(self, eventDict): system = eventDict['system'] if system == '-': system = 'twisted' else: system = 'twisted.' + system logger = logging.getLogger(system) # This next line is obnoxious. --Dave #logger.setLevel(logging.DEBUG) edm = eventDict['message'] or '' if eventDict['isError'] and eventDict.has_key('failure'): if not edm: edm = 'Failure:' logger.log(self.error_log_level, edm, exc_info=eventDict['failure'].exc_info()) elif eventDict.has_key('format'): try: text = self._safeFormat(eventDict['format'], eventDict) except: try: text = eventDict['format']%eventDict; except: text = repr(eventDict); logger.log(self.info_log_level, text) else: text = ' '.join(map(reflect.safe_str, edm)) logger.log(self.info_log_level, text)
Example #17
Source File: test_reflect.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def testWorkingStr(self): x = [1,2,3] self.assertEquals(reflect.safe_str(x), str(x))
Example #18
Source File: test_reflect.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def testBrokenStr(self): b = Breakable() b.breakStr = True reflect.safe_str(b)
Example #19
Source File: test_reflect.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def testBrokenClassStr(self): class X(BTBase): breakStr = True reflect.safe_str(X) reflect.safe_str(X())
Example #20
Source File: test_reflect.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def testBrokenClassRepr(self): class X(BTBase): breakRepr = True reflect.safe_str(X) reflect.safe_str(X())
Example #21
Source File: test_reflect.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def testBroken__Class__Attr(self): reflect.safe_str(NoClassAttr())
Example #22
Source File: test_reflect.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def testBroken__Class__Name__Attr(self): class X(BTBase): breakName = True reflect.safe_str(X())
Example #23
Source File: __init__.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def call_responder(protocol, command, arguments): """Call `command` responder in `protocol` with given `arguments`. Serialises the arguments and deserialises the response too. """ responder = protocol.locateResponder(command.commandName) arguments = command.makeArguments(arguments, protocol) d = responder(arguments) d.addCallback(command.parseResponse, protocol) def eb_massage_error(error): if error.check(amp.RemoteAmpError): # Convert remote errors back into local errors using the # command's error map if possible. error_type = command.reverseErrors.get( error.value.errorCode, amp.UnknownRemoteError ) return Failure(error_type(error.value.description)) else: # Exceptions raised in responders that aren't declared in that # responder's schema can get through to here without being wrapped # in RemoteAmpError. This is because call_responder() bypasses the # network marshall/unmarshall steps, where these exceptions would # ordinarily get squashed. return Failure( amp.UnknownRemoteError( "%s: %s" % (reflect.qual(error.type), reflect.safe_str(error.value)) ) ) d.addErrback(eb_massage_error) return d
Example #24
Source File: test_reflect.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_unicode(self): """ A unicode string is encoded to ``ascii`` with ``backslashreplace`` error handling on Python 2. """ unicodeString = u'\N{DOUBLE EXCLAMATION MARK} !!' safe = reflect.safe_str(unicodeString) self.assertEqual(safe, b'\u203c !!')
Example #25
Source File: log.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
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
Example #26
Source File: failure.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def getErrorMessage(self): """Get a string of the exception which caused this Failure.""" if isinstance(self.value, Failure): return self.value.getErrorMessage() return reflect.safe_str(self.value)
Example #27
Source File: test_reflect.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_workingStr(self): x = [1, 2, 3] self.assertEqual(reflect.safe_str(x), str(x))
Example #28
Source File: test_reflect.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_brokenStr(self): b = Breakable() b.breakStr = True reflect.safe_str(b)
Example #29
Source File: test_reflect.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_workingUtf8_2(self): """ L{safe_str} for C{str} with utf-8 encoded data should return the value unchanged. """ x = b't\xc3\xbcst' self.assertEqual(reflect.safe_str(x), x)
Example #30
Source File: test_reflect.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_workingUtf8_3(self): """ L{safe_str} for C{bytes} with utf-8 encoded data should return the value decoded into C{str}. """ x = b't\xc3\xbcst' self.assertEqual(reflect.safe_str(x), x.decode('utf-8'))