Serialize NIO

This commit is contained in:
Julien Duponchelle committed 2015-01-16 17:09:45 +01:00
1 parent 0cdc1c3042
commit bf6f62e629
11 files changed
+65 -26

No files matched your search

+11
View File
@@ -18,7 +18,9 @@
import json
import jsonschema
import aiohttp.web
import logging
log = logging.getLogger(__name__)
class Response(aiohttp.web.Response):
@@ -29,13 +31,22 @@ class Response(aiohttp.web.Response):
headers['X-Route'] = self._route
super().__init__(headers=headers, **kwargs)
"""
Set the response content type to application/json and serialize
the content.
:param anwser The response as a Python object
"""
def json(self, answer):
"""Pass a Python object and return a JSON as answer"""
self.content_type = "application/json"
if hasattr(answer, '__json__'):
answer = answer.__json__()
if self._output_schema is not None:
try:
jsonschema.validate(answer, self._output_schema)
except jsonschema.ValidationError as e:
log.error("Invalid output schema")
raise aiohttp.web.HTTPBadRequest(text="{}".format(e))
self.body = json.dumps(answer, indent=4, sort_keys=True).encode('utf-8')
+4
View File
@@ -19,6 +19,9 @@ import json
import jsonschema
import asyncio
import aiohttp
import logging
log = logging.getLogger(__name__)
from ..modules.vm_error import VMError
from .response import Response
@@ -37,6 +40,7 @@ def parse_request(request, input_schema):
try:
jsonschema.validate(request.json, input_schema)
except jsonschema.ValidationError as e:
log.error("Invalid input schema")
raise aiohttp.web.HTTPBadRequest(text="Request is not {} '{}' in schema: {}".format(
e.validator,
e.validator_value,