Skip to content

Commit

Permalink
Setting Content-Type: text/plain for DELETE responses
Browse files Browse the repository at this point in the history
  • Loading branch information
ElSaico committed Jun 28, 2016
1 parent a4994eb commit 116da9f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
10 changes: 8 additions & 2 deletions restless/dj.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt

from .constants import OK, NO_CONTENT
from .exceptions import NotFound
from .resources import Resource

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

def build_response(self, data, status=200):
def build_response(self, data, status=OK):
# By default, Django-esque.
resp = HttpResponse(data, content_type='application/json')
if status == NO_CONTENT:
# Avoid crashing the client when it tries to parse nonexisting JSON.
content_type = 'text/plain'
else:
content_type = 'application/json'
resp = HttpResponse(data, content_type=content_type)
resp.status_code = status
return resp

Expand Down
23 changes: 22 additions & 1 deletion tests/test_dj.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def fake_init(self):
]

def is_authenticated(self):
if self.request_method() == 'DELETE':
if self.request_method() == 'DELETE' and self.endpoint == 'list':
return False

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

def delete(self, pk):
for i, item in enumerate(self.fake_db):
if item.id == pk:
del self.fake_db[i]
return

@skip_prepare
def schema(self):
# A WILD SCHEMA VIEW APPEARS!
Expand Down Expand Up @@ -340,3 +346,18 @@ def test_create(self):
'id': 6,
'title': 'Moved hosts'
})

def test_delete(self):
self.res.request = FakeHttpRequest('DELETE')
self.assertEqual(len(self.res.fake_db), 3)

resp = self.res.handle('detail', pk=2)
self.assertEqual(resp['Content-Type'], 'text/plain')
self.assertEqual(resp.status_code, 204)
self.assertEqual(resp.content.decode('utf-8'), '')

# Check the internal state.
self.res.request = FakeHttpRequest('GET')
self.assertEqual(len(self.res.fake_db), 2)
resp = self.res.handle('detail', pk=2)
self.assertEqual(resp.status_code, 404)

0 comments on commit 116da9f

Please sign in to comment.