Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions django_declarative_apis/resources/emitters.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,19 +183,23 @@ def decode(self, data):
def render(self, request):
cb = request.GET.get("callback", None)
assert cb is None, "JSONP Callbacks not suppoted"
seria = json.dumps(
self.decode(self.construct()),
cls=DjangoJSONEncoder,
ensure_ascii=False,
indent=4,
)
seria = self.decode(self.construct())
if isinstance(seria, list):
if len(seria) == 0 or (len(seria) == 1 and len(seria[0]) == 0):
Copy link
Collaborator

@bgrant bgrant Jul 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume in some cases self.decode returns a tuple or something and that's the cause of the clause after the or? Is there a possibility of guessing this wrong and getting an IndexError on that seria[0]?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The base case (len == 0) is a just in case. What we actually see with our current issue is [""]. No, if we have a list of length 1, it would always be accessible and have a length given it's a string (val.decode("utf8") in self.decode)

# the body is empty, no need to run json.dumps
return ""

# Callback
# TODO: do we care about JSONP?
# if cb and is_valid_jsonp_callback_value(cb):
# return '%s(%s)' % (cb, seria)

return seria
return json.dumps(
seria,
cls=DjangoJSONEncoder,
ensure_ascii=False,
indent=4,
)


Emitter.register("json", JSONEmitter, "application/json; charset=utf-8")
Expand Down
5 changes: 5 additions & 0 deletions tests/resources/test_emitters.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ def test_decode(self):
resp = em.render(django.test.RequestFactory().get("/"))
self.assertEqual(json.loads(resp), ["foo", "bar"])

def test_decode_empty_list(self):
em = emitters.JSONEmitter([""], lambda: None)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for completeness don't we want another test with a truly empty list?

resp = em.render(django.test.RequestFactory().get("/"))
self.assertEqual(resp, "")


class DjangoEmitterTestCase(unittest.TestCase):
def test_render_http_response_succes(self):
Expand Down