Skip to content

Instantly share code, notes, and snippets.

@gartmeier
Created November 6, 2019 17:01
Show Gist options
  • Save gartmeier/7d794b26531f0cc03043ff666980fe50 to your computer and use it in GitHub Desktop.
Save gartmeier/7d794b26531f0cc03043ff666980fe50 to your computer and use it in GitHub Desktop.
CamelCaseJSONParser with skip_keys
# -*- coding: utf-8 -*-
import json
import six
from django.conf import settings
from django.core.files import File
from django.http import QueryDict
from django.utils import six
from djangorestframework_camel_case.settings import api_settings
from djangorestframework_camel_case.util import _get_iterable, camel_to_underscore, is_iterable
from rest_framework.exceptions import ParseError
def underscoreize(data, **options):
if isinstance(data, dict):
new_dict = {}
for key, value in _get_iterable(data):
try:
if key in options['skip_keys']:
new_dict[key] = value
continue
except TypeError:
pass
if isinstance(key, six.string_types):
new_key = camel_to_underscore(key, **options)
else:
new_key = key
new_dict[new_key] = underscoreize(value, **options)
if isinstance(data, QueryDict):
new_query = QueryDict(mutable=True)
for key, value in new_dict.items():
new_query.setlist(key, value)
return new_query
return new_dict
if is_iterable(data) and not isinstance(data, (six.string_types, File)):
return [underscoreize(item, **options) for item in data]
return data
class CamelCaseJSONParser(api_settings.PARSER_CLASS):
def parse(self, stream, media_type=None, parser_context=None):
parser_context = parser_context or {}
encoding = parser_context.get("encoding", settings.DEFAULT_CHARSET)
try:
data = stream.read().decode(encoding)
return underscoreize(json.loads(data), **api_settings.JSON_UNDERSCOREIZE)
except ValueError as exc:
raise ParseError("JSON parse error - %s" % six.text_type(exc))
REST_FRAMEWORK = {
...
'DEFAULT_PARSER_CLASSES': (
'api.parser.CamelCaseJSONParser',
),
'JSON_UNDERSCOREIZE': {
'skip_keys': ['metadata']
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment