[PYTHON] [Django] Use MessagePack with Django REST framework

Use MessagePack with Django REST framework

By default, the HTTP request / response of the Django REST framework application assumes JSON. JSON is good, but you want to use MessagePack.

To change this, set Parsers / Renderers.

Request --Parsers Response --Renderers

MessagePack is not supported by default, but the documentation says to use djangorestframework-msgpack.

MessagePack is a fast, efficient binary serialization format.
Juan Riaza maintains the djangorestframework-msgpack package which provides MessagePack renderer and parser support for REST framework.

djangorestframework-msgpack

Install djangorestframework-msgpack.

pip install djangorestframework-msgpack

Set setting.py to use MessagePack.

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework_msgpack.parsers.MessagePackParser',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework_msgpack.renderers.MessagePackRenderer',
    ),
}

You are now using MessagePack.

The rest is a bonus.

Also use Django REST Swagger

I'm using Django REST Swagger, but I don't know how to use MessagePack.

Therefore, in the environment that uses Swagger (here, when DEBUG = True), JSON is also available.

if DEBUG == True:
    REST_FRAMEWORK = {
        'DEFAULT_PARSER_CLASSES': (
            'rest_framework_msgpack.parsers.MessagePackParser',
            'rest_framework.parsers.JSONParser',
        ),
        'DEFAULT_RENDERER_CLASSES': (
            'rest_framework_msgpack.renderers.MessagePackRenderer',
            'rest_framework.renderers.JSONRenderer',
            'rest_framework.renderers.BrowsableAPIRenderer',
        ),
    }
else:
    REST_FRAMEWORK = {
        'DEFAULT_PARSER_CLASSES': (
            'rest_framework_msgpack.parsers.MessagePackParser',
        ),
        'DEFAULT_RENDERER_CLASSES': (
            'rest_framework_msgpack.renderers.MessagePackRenderer',
        ),
    }

The order is important. Since the top is the main, I will write the Message Pack as the main.

BrowsableAPIRenderer is for this. I'm not using it now, but I put it in.

Communication test is done with MessagePack

Write to use MessagePack when testing communication. It doesn't make sense to test with JSON.

import msgpack

from django.test import TestCase

class ApiUsersTestCase(TestCase):
    def test_put_users_pk_ok(self):
        """
For example, an API that sets user parameters
Since it is an image, only a simple test
        """
        
        pk = 1
        params = {
            "name": "Playing cards"
        }

        response = self.client.put("/users/{0}/".format(pk), msgpack.packb(params, use_bin_type=True), "application/msgpack")
        self.assertEqual(response.status_code, 201)
        
        content = msgpack.unpackb(response.content, encoding='utf-8')
        self.assertEqual(content["name"], params["name"])

Recommended Posts

[Django] Use MessagePack with Django REST framework
Django REST framework with Vue.js
Login with django rest framework
Create RESTful APIs with Django Rest Framework
CRUD POST with Nuxt & Django REST Framework
CRUD GET with Nuxt & Django REST Framework ①
Use Gentelella with django
Django REST framework basics
Use LESS with Django
Use MySQL with Django
Django Rest Framework Tips
CRUD PUT, DELETE with Nuxt & Django REST Framework
Implementing authentication in Django REST Framework with djoser
Django REST framework stumbling block
Use prefetch_related conveniently with Django
Create a Todo app with Django REST Framework + Angular
When you want to filter with Django REST framework
Implement hierarchical URLs with drf-nested-routers in Django REST framework
Use Unicode 6.0 emoji with django / MySQL
Implementation of CRUD using REST API with Python + Django Rest framework + igGrid
Create a REST API to operate dynamodb with the Django REST Framework
Logical deletion in Django, DRF (Django REST Framework)
Understand the benefits of the Django Rest Framework
ng-admin + Django REST framework ready-to-create administration tool
Miscellaneous notes about the Django REST framework
Django REST Framework + Clean Architecture Design Consideration
Implementation of custom user model authentication in Django REST Framework with djoser
Internationalization with django
CRUD with Django
How to deal with garbled characters in json of Django REST Framework
Use additional Python packages with Serverless Framework (v1.x)
Django REST framework A little useful to know.
Implement JWT login functionality in Django REST framework
Use Python / Django with Windows Azure Cloud Service!
How to automatically generate API document with Django REST framework & POST from document screen
Authenticate Google with Django
Django 1.11 started with Python3.6
Upload files with Django
Development digest with Django
Use RTX 3090 with PyTorch
Use ansible with cygwin
Django python web framework
Use pipdeptree with virtualenv
Output PDF with Django
[Python] Use JSON with Python
Use Mock with pytest
Markdown output with Django
Twitter OAuth with Django
Use tensorboard with Chainer
Use DynamoDB with Python
Use pip with MSYS2
Getting Started with Django 1
Sometimes you want to access View information from Serializer with DRF (Django REST Framework)
List method for nested resources in Django REST framework
Implement APIs at explosive speed using Django REST Framework
Use Python 3.8 with Anaconda
Use pyright with Spacemacs
File upload with django
Use python with docker
[Django Rest Framework] Customize the filter function using Django-Filter
Pooling mechanize with Django