Git Product home page Git Product logo

drf_orjson_renderer's Introduction

Django Rest Framework ORJSON Renderer

DRF ORJSON Renderer Tests

drf_orjson_renderer is JSON renderer and parser for Django Rest Framework using the orjson library. Backed by Rust, orjson is safe, correct and fast. ⚡️

In addition, unlike some performance optimized DRF renderers, It also renders pretty printed JSON when requests are made via RestFramework's BrowsableAPI.

You get:

  • The safety of Rust
  • The speed of orjson when requests are made with Accept: appliation/json HTTP header or when requests are made with an unspecified Accept header.
  • The convenience of formatted output when requested with Accept: text/html.
  • The ability to pass your own default function definition.

Installation

pip install drf_orjson_renderer

You can then set the ORJSONRenderer class as your default renderer in your settings.py

REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": (
        "drf_orjson_renderer.renderers.ORJSONRenderer",
        "rest_framework.renderers.BrowsableAPIRenderer",
    ),
}

To modify how data is serialized, specify options in your settings.py

REST_FRAMEWORK = {
    "ORJSON_RENDERER_OPTIONS": (
        orjson.OPT_NON_STR_KEYS,
        orjson.OPT_SERIALIZE_DATACLASS,
        orjson.OPT_SERIALIZE_NUMPY,
    ),
}

Also you can set the ORJSONParser class as your default parser in your settings.py

REST_FRAMEWORK = {
    "DEFAULT_PARSER_CLASSES": (
        "drf_orjson_renderer.parsers.ORJSONParser",
    ),
}

Passing Your Own default Function

By default, the ORJSONRenderer will pass a default function as a helper for serializing objects that orjson doesn't recognize. That should cover the most common cases found in a Django web application. If you find you have an object it doesn't recognize you can pass your own default function by overriding the get_renderer_context() method of your view:

from rest_framework.views import APIView
from rest_framework.response import Response


class MyView(APIView):
    def default(self, obj):
        if isinstance(obj, MyComplexData):
            return dict(obj)

    def get_renderer_context(self):
        renderer_context = super().get_renderer_context()
        renderer_context["default_function"] = self.default
        return renderer_context

    def get(self, request, *args, **kwargs):
        my_complex_data = MyComplexData()
        return Response(data=my_complex_data)

If you know your data is already in a format orjson natively recognizes you can get a small performance boost by passing None to the renderer_context:

def get_renderer_context(self):
    renderer_context = super().get_renderer_context()
    renderer_context["default_function"] = None
    return renderer_context

As of ORJSON version 3, 2-space indenting is supported in serialization. In order to take advantage of the RestFramework Browsable API, when the requested media type is not application/json, the ORJSON renderer will add orjson.OPT_INDENT_2 to the options mask to pretty print your output.

Numpy

When this package was originally written ORJSON did not natively support serializing numpy types. This package provided an encoder class that overrides the DjangoJSONEncoder with support for numpy types. This encoder is no longer necessary but included for backwards compatibility.

from drf_orjson_renderer.encoders import DjangoNumpyJSONEncoder
from rest_framework.views import APIView

class MyView(APIView):


    def get_renderer_context(self):
        renderer_context = super().get_renderer_context()
        renderer_context["django_encoder_class"] = DjangoNumpyJSONEncoder
        return renderer_context

Benchmarks

See the orjson Benchmarks for more information

drf_orjson_renderer's People

Contributors

brianjbuck avatar cblakkan avatar dependabot[bot] avatar dvazar avatar falsetru avatar jsmolina avatar sidmitra avatar uninen avatar yuekui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

drf_orjson_renderer's Issues

Update to Django 4.0

Currently RestFramework does not support Django 4.0 deprecation of pytz:

/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/rest_framework/fields.py:32: in <module>
    from pytz.exceptions import InvalidTimeError
E   ModuleNotFoundError: No module named 'pytz'

Update to Django 4.0 when Restframework is released.

Render problem

Lazy project objects such as lazy translations are not rendered properly. They are not actual strings and have iter method, so rederer renders them as list of chars

Dependency resolution fails with Django versions 4.0.x

Dependency resolution fails when installing drf-orjson-renderer with the latest Django version (4.0.6). The pinned version is too specific.

I would suggest changing it from "django>=3.2,<=4.0" to "django>=3.2,<4.1" and re-releasing to PyPi.

drf_orjson_render 1.4.0 fail.

My application breaks after upgrading to drf_orjson_render 1.4.0

ERROR    django.request:log.py:224 Internal Server Error: /path-replaced/97336477996045/55391693115234
Traceback (most recent call last):
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/falsetru/work/project-name-replaced-project/targetyo/util/db.py", line 53, in inner
    return f(*args, **kwargs)
  File "/home/falsetru/work/project-name-replaced-project/targetyo/api/decorators.py", line 36, in wrapper
    return func(request, *args, **kwargs)
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch
    self.initial(request, *args, **kwargs)
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/rest_framework/views.py", line 406, in initial
    neg = self.perform_content_negotiation(request)
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/rest_framework/views.py", line 310, in perform_content_negotiation
    return conneg.select_renderer(request, renderers, self.format_kwarg)
  File "/home/falsetru/.virtualenvs/project-name-replaced/lib/python3.8/site-packages/rest_framework/negotiation.py", line 65, in select_renderer
    full_media_type = ';'.join(
TypeError: sequence item 0: expected str instance, NoneType found

I think this is caused by ORJSONRenderer.media_type change in 9dddb21#diff-af3668e3a8a4fd6a0dcb9a8d9a2550ac2f7fb3e562e2f5f94be73b28b0770684L21

In 1.3:

>>> from drf_orjson_renderer.renderers import ORJSONRenderer
>>> ORJSONRenderer.media_type
'application/json'

In 1.4:

>>> from drf_orjson_renderer.renderers import ORJSONRenderer
>>> ORJSONRenderer.media_type  # None
>>> 

Packages used:

  • Django==3.2.10
  • djangorestframework==3.12.4
  • drf-orjson-renderer==1.4.0

REST_FRAMEWORK:

REST_FRAMEWORK = {                                                                                                                                                                                         
    "DEFAULT_RENDERER_CLASSES": [
        "drf_orjson_renderer.renderers.ORJSONRenderer",
        "rest_framework.renderers.BrowsableAPIRenderer",
    ],
    "TIME_FORMAT": "%H:%M:%S",
}

Add CI configuration

Could add Travis CI or GitHub actions to automatically run the test suite on all code for each new commit or PR that is submitted.

The drf_ujson2 repository has a good setup that could be used as an example.

ORJSONRenderer is causing malformed response on 204 replies

how to reproduce?

Just add this reply to any view:
return Response(status=status.HTTP_204_NO_CONTENT)

rest_framework/response.py
ret = renderer.render(self.data, accepted_media_type, context)
will return 'null', and it will end in a malformed http response.

It is not happening on rest_framework.renderers.JSONRenderer as it has:

def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Render `data` into JSON, returning a bytestring.
        """
        if data is None:
            return b''

ChoicesMeta is deprecated in favor of ChoicesType.

Today I updated to django 5.0 and got the following warning:

/usr/local/lib/python3.12/site-packages/drf_orjson_renderer/renderers.py:8: RemovedInDjango60Warning: ChoicesMeta is deprecated in favor of ChoicesType.
from django.db.models.enums import ChoicesMeta

Django 6.0 isn't coming until around 2026 so I guess there is no hurry

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.