Hacker News new | ask | show | jobs
by pindi 4805 days ago
> Django does not have a built in JSON HTTP response, so you are going to have to either man up and roll your own (good luck)

Am I missing something? What's wrong with:

   return HttpResponse(json.dumps(data), mimetype='application/json')
Wrap it up in a convenience function and you're done.

The JSONResponse class suggested automatically implements JSONP, which is extremely dangerous. Consider a view on /accounts/info which returns some information about the currently logged in user. A malicious site could embed

  <script src="http://example.com/accounts/info?callback=someFunction">
and access the account information of any user logged into your site. JSONP is a technique to bypass the same-origin policy in appropriate cases; don't just blindly apply it everywhere or you're giving up the protection of the policy.
3 comments

might also be worth noting that django-tastypie is the defacto standard for REST apis, and sends and returns json (among many other serialization formats) very easily. This obviously doesn't work for all ajax cases, but its extremely useful nonetheless.
I would recommend Django Rest Framework. It gives you more fine grained control. We just use the serialisers for example.
json.dumps() can be dangerous if used on your raw domain data. You should specify the exact schema being sent down to the client so you don't accidentally leak something (this can happen very easily in Python)
Well, not dangerous so much as will fail with a "Model instance is not JSON serializable" message. So of course you'll need to construct the list/dictionary representation of your data manually. A good framework can help with that, but this isn't something that's solvable in the general case with just a response subclass without risking data leaks as you stated. (The other option in the original post makes this mistake, making both suggested options insecure)
yep, I build response objects ( my own term, not great but it describes what they are ) that are basic subsets of the object that I want to serialize to json. That way I'm sure only the fields that I really want to send are making it out.
Cool, I think a good JSONResponse implementation would bake that into the framework such that it's difficult to make the mistake you didn't make :)
I would guess complex objects - containers, or strange databasey stuff.

The way to deal with is __complex__ as a method on the object and recurse through asking the complex method to return nested simpler python types.

__complex__ is for converting to a complex number.
yeah, danellis is right. don't use __complex__ for that. it's for complex numbers:

http://docs.python.org/2/library/functions.html#complex --and-- http://docs.python.org/2/library/cmath.html