Skip to content
This repository was archived by the owner on Mar 18, 2019. It is now read-only.
This repository was archived by the owner on Mar 18, 2019. It is now read-only.

CamelCase CoreJSON Codec for easier integration with non-Python clients #162

Description

@Sonictherocketman

I've been integrating the new DRF Schemas into my app and converting it to use the CoreAPI JS client. Overall the process has been super smooth, however there's some inconsistencies in variable casing between my API (which uses djangorestframework_camel_case to render responses in a more JS friendly format) and my schema (which does not support this).

I've spent some time messing with it and I've gotten a subclass of the SchemaJSView to render camelcase using the same renderer as the rest of my app.

While this works for me, I'd love to see support for this added to DRF and CoreAPI for others to more easily use. Please let me know what you think and how I could PR this to CoreAPI and DRF.

My CamelCaseCoreAPI Codec

importjsonfromcoreapi.compatimportCOMPACT_SEPARATORS, VERBOSE_SEPARATORSfromcoreapi.compatimportforce_bytes, string_types, urlparsefromcoreapi.codecs.corejsonimport (
CoreJSONCodec, _document_to_primitive, _primitive_to_document
)
fromcoreapi.documentimportDocument, Link, Array, Object, Error, Fieldfromdjangorestframework_camel_case.utilimportcamelize, underscoreizeclassCamelCaseCoreJSONCodec(CoreJSONCodec):
""" A subclass of the CoreAPI CoreJSON Codec, that additionally performs a simple transformation to CamelCase-style syntax for easy consumption by Javascript and other similar clients. """defdecode(self, bytestring, **options):
""" Takes a bytestring and returns a document. """base_url=options.get('base_url')
try:
data=underscoreize(json.loads(bytestring.decode('utf-8')))
exceptValueErrorasexc:
raiseParseError('Malformed JSON. %s'%exc)
doc=_primitive_to_document(data, base_url)
ifisinstance(doc, Object):
doc=Document(content=dict(doc))
elifnot (isinstance(doc, Document) orisinstance(doc, Error)):
raiseParseError('Top level node should be a document or error.')
returndocdefencode(self, document, **options):
""" Takes a document and returns a bytestring. """indent=options.get('indent')
ifindent:
kwargs= {
'ensure_ascii': False,
'indent': 4,
'separators': VERBOSE_SEPARATORS
}
else:
kwargs= {
'ensure_ascii': False,
'indent': None,
'separators': COMPACT_SEPARATORS
}
data=_document_to_primitive(document)
returnforce_bytes(json.dumps(camelize(data), **kwargs))

Note: In messing around I found that I needed to repeat a lot of the CoreJSONCodec in my code. I'm wondering if we can tweak the CoreJSONCodec a bit to more elegantly do the encoding/decoding.

Edit: wording.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions