KaruMediaServer/api/karumedia/tools.py

70 lines
1.9 KiB
Python
Raw Normal View History

2016-11-01 22:26:29 +02:00
import json
2017-01-21 21:51:11 +02:00
import datetime
2016-11-01 22:26:29 +02:00
from falcon import Request as FalconRequest
from falcon import Response as FalconResponse
2017-01-21 21:51:11 +02:00
from falcon.errors import HTTPBadRequest, HTTPMissingParam, HTTPError, HTTPNotFound
2016-11-01 22:26:29 +02:00
import falcon.status_codes as status
2017-01-21 21:51:11 +02:00
from bson.objectid import ObjectId
from mongoengine import DoesNotExist
class BSONDumps(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, ObjectId):
return str(obj)
elif isinstance(obj, datetime.datetime):
return obj.timestamp()
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
dumps = BSONDumps(indent=4).encode
2016-11-01 22:26:29 +02:00
class JsonRequest(FalconRequest):
2016-11-01 23:17:23 +02:00
#__slots__ = set(FalconRequest.__slots__ + ("_json", "_args"))
2016-11-01 22:26:29 +02:00
@property
def json(self):
if not hasattr(self, "_json"):
if not self.client_accepts_json:
raise falcon.HTTPUnsupportedMediaType(
'This API only supports the JSON formated data')
try:
self._json = json.loads(self.stream.read().decode('utf8'))
except json.decoder.JSONDecodeError as err:
raise HTTPBadRequest("JSONDecodeError", str(err))
return self._json
class JsonResponse(FalconResponse):
2016-11-01 23:17:23 +02:00
#__slots__ = set(FalconRequest.__slots__ + ("_json",))
2016-11-01 22:26:29 +02:00
@property
def json(self):
return self._json
@json.setter
def json(self, value):
self._json = value
2017-01-21 21:51:11 +02:00
self.body = dumps(value)
2016-11-01 22:26:29 +02:00
def error_handler(ex, req, resp, params):
2017-01-21 21:51:11 +02:00
if type(ex).__name__ == DoesNotExist.__name__:
raise HTTPNotFound(title=type(ex).__name__, description=str(ex))
else:
raise HTTPBadRequest(type(ex).__name__, str(ex))
2016-11-01 22:26:29 +02:00
class TODOException(HTTPError):
def __init__(self, **kwargs):
super(TODOException, self).__init__(status.HTTP_NOT_IMPLEMENTED, **kwargs)
@property
def has_representation(self):
return False