Django: introducing django-orjson

Just as cars painted red are known to be faster, libraries implemented in Rust are also known to be faster. Today’s example is orjson, a Rusty replacement for Python’s built-in json module, boasting 10x faster serialization and 2x faster deserialization.
Such a library is great, but adopting it isn’t easy, especially when your framework uses json in many different parts. To help Django developers adopt orjson, I have created django-orjson, which provides a whole bunch of drop-in replacements for Django and Django REST Framework (DRF) components backed by orjson.
For example, there’s a version of JsonResponse:
from django_orjson.http import JsonResponse
def index(request):
return JsonResponse({"title": "Hello, world!"})
…a test client with matching test case classes:
from django_orjson.test import SimpleTestCase
class IndexTests(SimpleTestCase):
def test_index(self):
response = self.client.get("/", headers={"accept": "application/json"})
assert response.status_code == 200
# response.json() uses orjson to parse the response body
assert response.json() == {"title": "Hello, world!"}
…a version of Django’s json_script template tag:
{% load django_orjson %}
{{ chart_data|json_script:"chart-data" }}
…and plenty more! All tested against the currently supported versions of Python and Django with 100% branch coverage.
While database queries tend to dominate the typical Django application’s runtime, the time spent in serialization and deserialization can still be significant. That can make adopting orjson a nearly free performance win, which I hope django-orjson makes almost trivial for you.
Django proposal
After seeing the initial version of django-orjson, Paolo Melchiorre decided to push for adding orjson support to Django itself, in the new feature proposal Pluggable JSON serialization/deserialization backend. He made a thorough list of all the places in Django that could use orjson, and the proposal has gathered 14 thumbs-ups at the time of writing.
If you’re interested in the topic of speeding up Django’s JSON handling, check out the proposal and add your thoughts to the discussion.
😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸
One summary email a week, no spam, I pinky promise.
Related posts:
Tags: django