Validate hooks with serde
This commit is contained in:
parent
a15ebaf82c
commit
20a4e21eaa
|
@ -0,0 +1,18 @@
|
|||
from serde import Model, fields
|
||||
|
||||
class Market(Model):
|
||||
exchange = fields.Str()
|
||||
item = fields.Str()
|
||||
currency = fields.Str()
|
||||
contract = fields.Str()
|
||||
|
||||
class Timestamp(Model):
|
||||
sent = fields.DateTime()
|
||||
trade = fields.DateTime()
|
||||
|
||||
class BaseDrakdoo(Model):
|
||||
title = fields.Str()
|
||||
message = fields.Str()
|
||||
period = fields.Str()
|
||||
market = fields.Nested(Market)
|
||||
timestamp = fields.Nested(Timestamp)
|
|
@ -11,6 +11,11 @@ from rest_framework.views import APIView
|
|||
from core.forms import HookForm
|
||||
from core.models import Callback, Hook
|
||||
|
||||
from core.lib.serde import drakdoo
|
||||
from serde import ValidationError
|
||||
from util import log
|
||||
|
||||
log = log.get_logger(__name__)
|
||||
|
||||
def get_hooks(user):
|
||||
hooks = Hook.objects.filter(user=user)
|
||||
|
@ -21,19 +26,36 @@ class HookAPI(APIView):
|
|||
parser_classes = [JSONParser]
|
||||
|
||||
def post(self, request, hook_name):
|
||||
print("DATA", request.data)
|
||||
log.debug(f"HookAPI POST: {request.data}")
|
||||
|
||||
# Try loading the JSON
|
||||
try:
|
||||
loaded_json = orjson.loads(request.data)
|
||||
except orjson.JSONDecodeError:
|
||||
return HttpResponseBadRequest("Invalid JSON")
|
||||
|
||||
# Try validating the JSON
|
||||
try:
|
||||
hook_resp = drakdoo.BaseDrakdoo.from_dict(loaded_json)
|
||||
except ValidationError as e:
|
||||
log.error(f"HookAPI POST: {e}")
|
||||
return HttpResponseBadRequest(e)
|
||||
|
||||
# Try getting the hook
|
||||
try:
|
||||
hook = Hook.objects.get(hook=hook_name)
|
||||
except Hook.DoesNotExist:
|
||||
return HttpResponseBadRequest("Hook does not exist.")
|
||||
|
||||
# Create the callback object
|
||||
callback = Callback.objects.create(
|
||||
hook=hook,
|
||||
data=request.data,
|
||||
)
|
||||
callback.save()
|
||||
# Bump received count
|
||||
hook.received = hook.received + 1
|
||||
hook.save()
|
||||
print("SAVED")
|
||||
|
||||
return HttpResponse("OK")
|
||||
|
||||
|
|
|
@ -15,3 +15,4 @@ django-debug-toolbar-template-profiler
|
|||
orjson
|
||||
django-otp
|
||||
qrcode
|
||||
serde[ext]
|
||||
|
|
Loading…
Reference in New Issue