diff --git a/wsme/rest.py b/wsme/rest.py index f237c0b..550ff1e 100644 --- a/wsme/rest.py +++ b/wsme/rest.py @@ -1,14 +1,20 @@ import webob import sys +import logging from wsme.exc import UnknownFunction, MissingArgument, UnknownArgument +log = logging.getLogger(__name__) + html_body = """ + + + -
 %(content)s
-
""" @@ -36,11 +42,14 @@ class RestProtocol(object): if body is None and len(request.params): parsed_args = {} for key, value in request.params.items(): - parsed_args[key] = self.parse_arg(value) + parsed_args[key] = self.parse_arg(key, value) else: if body is None: body = request.body - parsed_args = self.parse_args(body) + if body: + parsed_args = self.parse_args(body) + else: + parsed_args = {} kw = {} @@ -93,9 +102,37 @@ class RestProtocol(object): # output format. if res_content_type is None: if "text/html" in request.accept: + res.body = self.html_format(res.body) res_content_type = "text/html" - res.body = html_body % dict(content=res.body) res.headers['Content-Type'] = "%s; charset=UTF-8" % res_content_type return res + + def html_format(self, content): + try: + from pygments import highlight + from pygments.lexers import get_lexer_for_mimetype + from pygments.formatters import HtmlFormatter + + lexer = None + for ct in self.content_types: + try: + print ct + lexer = get_lexer_for_mimetype(ct) + break + except: + pass + + if lexer is None: + raise ValueError("No lexer found") + formatter = HtmlFormatter() + return html_body % dict( + css=formatter.get_style_defs(), + content=highlight(content, lexer, formatter).encode('utf8')) + except Exception, e: + log.warning( + "Could not pygment the content because of the following error :\n%s" % e) + return html_body % dict( + css='', + content='
%s
' % content.replace('>', '>').replace('<', '<')) diff --git a/wsme/restjson.py b/wsme/restjson.py index 169d075..f55f1a2 100644 --- a/wsme/restjson.py +++ b/wsme/restjson.py @@ -90,12 +90,12 @@ def binary_fromjson(datatype, value): class RestJsonProtocol(RestProtocol): name = 'REST+Json' dataformat = 'json' - content_types = ['application/json', 'text/json', '', None] + content_types = ['application/json', 'application/javascript', 'text/json', '', None] def decode_arg(self, value, arg): return fromjson(arg.datatype, value) - def parse_arg(self, value): + def parse_arg(self, name, value): return json.loads(value) def parse_args(self, body): diff --git a/wsme/restxml.py b/wsme/restxml.py index 1381dcb..9a59e19 100644 --- a/wsme/restxml.py +++ b/wsme/restxml.py @@ -119,8 +119,8 @@ class RestXmlProtocol(RestProtocol): def decode_arg(self, value, arg): return fromxml(arg.datatype, value) - def parse_arg(self, value): - return et.fromstring(value) + def parse_arg(self, name, value): + return et.fromstring(u"<%s>%s" % (name, value, name)) def parse_args(self, body): return dict((sub.tag, sub) for sub in et.fromstring(body))