parsers.py 1.0 KB

123456789101112131415161718192021222324252627
  1. import codecs
  2. from django.conf import settings
  3. from rest_framework.parsers import JSONParser
  4. from rest_framework.exceptions import ParseError
  5. from rest_framework.utils import json
  6. class EnvelopeParser(JSONParser):
  7. media_type = "application/x-sentry-envelope"
  8. def parse(self, stream, media_type=None, parser_context=None):
  9. """
  10. Parses the incoming bytestream as JSON and returns the resulting data.
  11. Supports multiple lines of JSON objects
  12. """
  13. parser_context = parser_context or {}
  14. encoding = parser_context.get("encoding", settings.DEFAULT_CHARSET)
  15. try:
  16. decoded_stream = codecs.getreader(encoding)(stream)
  17. parse_constant = json.strict_constant if self.strict else None
  18. messages = []
  19. for line in decoded_stream:
  20. messages.append(json.loads(line, parse_constant=parse_constant))
  21. return messages
  22. except ValueError as exc:
  23. raise ParseError("JSON parse error - %s" % str(exc))