2012-02-25 15:39:38 +03:00
|
|
|
import json
|
|
|
|
from functools import partial
|
|
|
|
import pygments
|
|
|
|
from pygments.lexers import get_lexer_for_mimetype
|
|
|
|
from pygments.formatters.terminal256 import Terminal256Formatter
|
|
|
|
from pygments.lexer import RegexLexer, bygroups
|
|
|
|
from pygments import token
|
|
|
|
|
|
|
|
|
|
|
|
TYPE_JS = 'application/javascript'
|
|
|
|
|
|
|
|
|
|
|
|
class HTTPLexer(RegexLexer):
|
|
|
|
name = 'HTTP'
|
|
|
|
aliases = ['http']
|
|
|
|
filenames = ['*.http']
|
|
|
|
tokens = {
|
|
|
|
'root': [
|
|
|
|
(r'\s+', token.Text),
|
|
|
|
(r'(HTTP/[\d.]+\s+)(\d+)(\s+.+)', bygroups(
|
|
|
|
token.Operator, token.Number, token.String)),
|
|
|
|
(r'(.*?:)(.+)', bygroups(token.Name, token.String))
|
|
|
|
]}
|
|
|
|
|
|
|
|
|
|
|
|
highlight = partial(pygments.highlight,
|
|
|
|
formatter=Terminal256Formatter(style='native'))
|
|
|
|
highlight_http = partial(highlight, lexer=HTTPLexer())
|
|
|
|
|
|
|
|
|
2012-02-26 03:37:28 +03:00
|
|
|
def prettify_http(headers):
|
2012-02-26 03:43:44 +03:00
|
|
|
return highlight_http(headers)
|
2012-02-26 03:37:28 +03:00
|
|
|
|
2012-02-25 15:39:38 +03:00
|
|
|
|
2012-02-26 03:37:28 +03:00
|
|
|
def prettify_body(content, content_type):
|
|
|
|
content_type = content_type.split(';')[0]
|
2012-02-25 15:39:38 +03:00
|
|
|
if 'json' in content_type:
|
|
|
|
content_type = TYPE_JS
|
|
|
|
try:
|
|
|
|
# Indent JSON
|
2012-02-26 03:37:28 +03:00
|
|
|
content = json.dumps(json.loads(content),
|
|
|
|
sort_keys=True, indent=4)
|
2012-02-25 15:39:38 +03:00
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
try:
|
2012-02-26 03:37:28 +03:00
|
|
|
lexer = get_lexer_for_mimetype(content_type)
|
|
|
|
content = highlight(code=content, lexer=lexer)
|
|
|
|
if content:
|
|
|
|
content = content[:-1]
|
2012-02-25 15:39:38 +03:00
|
|
|
except Exception:
|
|
|
|
pass
|
2012-02-26 03:37:28 +03:00
|
|
|
return content
|
2012-02-25 15:39:38 +03:00
|
|
|
|