Skip to content

Commit 116da9f

Browse files
committed
Setting Content-Type: text/plain for DELETE responses
1 parent a4994eb commit 116da9f

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

Diff for: restless/dj.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from django.http import HttpResponse, Http404
77
from django.views.decorators.csrf import csrf_exempt
88

9+
from .constants import OK, NO_CONTENT
910
from .exceptions import NotFound
1011
from .resources import Resource
1112

@@ -30,9 +31,14 @@ def is_debug(self):
3031
# By default, Django-esque.
3132
return settings.DEBUG
3233

33-
def build_response(self, data, status=200):
34+
def build_response(self, data, status=OK):
3435
# By default, Django-esque.
35-
resp = HttpResponse(data, content_type='application/json')
36+
if status == NO_CONTENT:
37+
# Avoid crashing the client when it tries to parse nonexisting JSON.
38+
content_type = 'text/plain'
39+
else:
40+
content_type = 'application/json'
41+
resp = HttpResponse(data, content_type=content_type)
3642
resp.status_code = status
3743
return resp
3844

Diff for: tests/test_dj.py

+22-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def fake_init(self):
5151
]
5252

5353
def is_authenticated(self):
54-
if self.request_method() == 'DELETE':
54+
if self.request_method() == 'DELETE' and self.endpoint == 'list':
5555
return False
5656

5757
return True
@@ -82,6 +82,12 @@ def update(self, pk):
8282
def create_detail(self):
8383
raise ValueError("This is a random & crazy exception.")
8484

85+
def delete(self, pk):
86+
for i, item in enumerate(self.fake_db):
87+
if item.id == pk:
88+
del self.fake_db[i]
89+
return
90+
8591
@skip_prepare
8692
def schema(self):
8793
# A WILD SCHEMA VIEW APPEARS!
@@ -340,3 +346,18 @@ def test_create(self):
340346
'id': 6,
341347
'title': 'Moved hosts'
342348
})
349+
350+
def test_delete(self):
351+
self.res.request = FakeHttpRequest('DELETE')
352+
self.assertEqual(len(self.res.fake_db), 3)
353+
354+
resp = self.res.handle('detail', pk=2)
355+
self.assertEqual(resp['Content-Type'], 'text/plain')
356+
self.assertEqual(resp.status_code, 204)
357+
self.assertEqual(resp.content.decode('utf-8'), '')
358+
359+
# Check the internal state.
360+
self.res.request = FakeHttpRequest('GET')
361+
self.assertEqual(len(self.res.fake_db), 2)
362+
resp = self.res.handle('detail', pk=2)
363+
self.assertEqual(resp.status_code, 404)

0 commit comments

Comments
 (0)