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.
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.
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