开发者

Pitfalls of generating JSON in Django templates

I've found myself unsatisfied with Django's ability to render JSON data. If I use built in serializes then database foreign key relationships are not included in the data (only the keys). Also, it seems to be impossible to include custom data in the json feed that isn't part of the model being serialized.

As a test I implemented a template that开发者_如何转开发 rendered some JSON for the resultset of a particular model. I was able to include/exclude whatever parts of the model I wanted and was able to include custom data as well.

The test seemed to work well and wasn't slower than the recommended serialization methods.

Are there any pitfalls to this using this method of serialization?


While it's hard to say definitively whether this method has any pitfalls, it's the method we use in production as you control everything that is serialized, even if the underlying model is changed. We've been running a high traffic application in for almost two years using this method.

Hope this helps.


One problem might be escaping metacharacters like ". Django's template system automatically escapes dangerous characters, but it's set up to do that for HTML. You should look up exactly what the template escaping does, and compare that to what's dangerous in JSON. Otherwise, you could cause XSS problems.

You could think about constructing a data structure of dicts and lists, and then running a JSON serializer on that, rather than directly on your database model.


I don't understand why you see the choice as being either 'use Django serializers' or 'write JSON in templates'. The middle way, which to my mind is much more robust and fits your use case well, is to build up your data as Python lists/dictionaries and then simply use simplejson.dumps() to convert it to a JSON string.


We use this method to get custom JSON format consumed by datatables.net It was the easiest method we find to accomplish this task and it looks very fine with no problems so far.

You can find details here: http://datatables.net/development/server-side/django


So far, generating JSON from templates, we've run into the need to escape newlines. Looking at doing simplejson.dumps() next.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜