aiocoap.util.prettyprint module

A pretty-printer for known mime types


A wrapper around pygments.lexers.get_lexer_for_mimetype that takes subtypes into consideration and catches the custom hexdump mime type.


Given a CoAP message, reshape its payload into something human-readable. The return value is a triple (infos, mime, text) where text represents the payload, mime is a type that could be used to syntax-highlight the text (not necessarily related to the original mime type, eg. a report of some binary data that’s shaped like Markdown could use a markdown mime type), and some line of infos that give additional data (like the reason for a hex dump or the original mime type).

>>> from aiocoap import Message
>>> def build(payload, request_cf, response_cf):
...     response = Message(payload=payload, content_format=response_cf)
...     request = Message(accept=request_cf)
...     response.request = request
...     return response
>>> pretty_print(Message(payload=b"Hello", content_format=0))
([], 'text/plain;charset=utf8', 'Hello')
>>> print(pretty_print(Message(payload=b'{"hello":"world"}', content_format=50))[-1])
    "hello": "world"
>>> # Erroneous inputs still go to the pretty printer as long as they're
>>> #Unicode
>>> pretty_print(Message(payload=b'{"hello":"world', content_format=50))
(['Invalid JSON not re-formated'], 'application/json', '{"hello":"world')
>>> pretty_print(Message(payload=b'<>,', content_format=40))
(['Invalid application/link-format content was not re-formatted'], 'application/link-format', '<>,')
>>> pretty_print(Message(payload=b'a', content_format=60)) # doctest: +ELLIPSIS
(['Showing hex dump of application/cbor payload: CBOR value is invalid'], 'text/vnd.aiocoap.hexdump', '00000000  61 ...