parsers.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import logging
  2. import orjson
  3. from django.conf import settings
  4. from django.http import HttpRequest
  5. from ninja.parser import Parser
  6. from sentry_sdk import capture_message, set_context
  7. logger = logging.getLogger(__name__)
  8. class EnvelopeParser(Parser):
  9. def parse_body(self, request: HttpRequest):
  10. if (
  11. request.resolver_match
  12. and request.resolver_match.url_name == "event_envelope"
  13. ):
  14. if request.META.get("CONTENT_TYPE", None) in [
  15. "application/x-sentry-envelope",
  16. "application/octet-stream",
  17. "text/plain;charset=UTF-8",
  18. None,
  19. ]:
  20. result = [orjson.loads(line) for line in request.readlines()]
  21. if settings.EVENT_STORE_DEBUG:
  22. print(orjson.dumps(result))
  23. return result
  24. try:
  25. return orjson.loads(request.body)
  26. except orjson.JSONDecodeError:
  27. set_context(
  28. "incoming event",
  29. {"body": request.body, "headers": request.META},
  30. )
  31. message = f"Envelope API unexpected content type {request.META.get('CONTENT_TYPE')}"
  32. capture_message(message, level="warning")
  33. logger.warning(message)
  34. return orjson.loads(request.body)