Задать вопрос

Тел: +7 965 3737 888

489

Просмотров

4

Ответов

JSON view decorator

Use this decorator on a function that returns a dict to get a JSON view, with error handling.

Features:

Вопрос полезен? Да0/Нет0
file_4216.py(1.5Кб)
None

Ответы (4):

Ответskarphace:21.03.2012
Ответ полезен? Да0/Нет0

This has a problem with decimals. As of simplejson 2.1.0, you can use use_decimal=True. So switch this:

json = simplejson.dumps(response)

To this:

json = simplejson.dumps(response, use_decimal=True)

Ответsk:28.09.2009
Ответ полезен? Да0/Нет0

Can I get an example of how to use this? I saved it as 'json_view.py' within my app files, then used 'from project.app.json_view import json_view' at views.py and add '@json_view' at a view function I want to see in JSON, but browser react as a download and the file is a text file with the JSON inside. Is this ok? Can a javascript interact with a downloadable JSON?

Ответmikeshantz:09.01.2009
Ответ полезен? Да0/Нет0

Very nice! Thanks for this one.

Ответkrid:12.06.2008
Ответ полезен? Да0/Нет0

This is really useful, but there's one subtle bug. The dict returned from the wrapped function is altered by the wrapper. If the value happens to be something persistent in your application, odd and unexpected things will happen. We have an ajax method to send config data to the client, data that is used elsewhere in the application. I was seeing occasional errors about "result", and couldn't figure it out. I finally tracked it down to this wrapper.

The lines:

response = func(request, *a, **kw)
assert isinstance(response, dict)

Should be changed to:

func_val = func(request, *a, **kw)
assert isinstance(func_val, dict)
response = dict(func_val)

Or you can ditch the assert, and go with:

response = dict(func(request, *a, **kw))