Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

camelCase POST data in Django REST Framework

I see there is project called djangorestframework-camel-case, which allows to use JavaScript-ish camelCase with underscore_cased fields in Django REST serializers. So, basically, I can send:

{
    "camelCase": "foo"
}

And receive it with following Serializer:

class MySerializer(serializers.Serializer):
    session_id = serializers.CharField()

Does something similar for POST data exist? So I can send camelCase=foo via POST and receive it to an underscore_case field in my serializer?

I tried implementing my own parser based on FormParser:

class CamelCaseFormParser(FormParser):
    media_type = 'application/x-www-form-urlencoded'

    def __init__(self):
        print("initialized")

    def parse(self, stream, media_type=None, parser_context=None):
        print("parse")
        ...

And, after adding it to DEFAULT_PARSER_CLASSES in settings.py, while initialized is actually printed, parse is not. So it seems, in case of POST data, application/x-www-form-urlencoded parser is not used at all.

Since Serializers are used like that:

Serializer(data=request.data)

I'm thinking about subclassing Serializer and modifying data before it gets processed further, or even modifying it before creating a Serializer. But what I'm asking for is a more convenient way, working for all Serializers, without subclassing them.

like image 697
m4tx Avatar asked Aug 20 '15 11:08

m4tx


1 Answers

why not sticking with parsers?

from djangorestframework_camel_case.util import underscoreize
from rest_framework import parsers
from django.conf import settings
from django.http import QueryDict


class CamelCaseFormParser(parsers.FormParser):
    def parse(self, stream, media_type=None, parser_context=None):
        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        data = QueryDict(stream.read(), encoding=encoding)
        return underscoreize(data)

simple, working and properly placed...

like image 53
Jerzyk Avatar answered Sep 20 '22 15:09

Jerzyk