Django的tastypie。默认情况下,以JSON格式输出到浏览器

时间:2011-12-27 21:17:54

标签: django json tastypie

我看到'抱歉,尚未实施。请附加“?format = json” 你的网址。'我需要总是附加字符串“?format = json”。我可以做一个 默认输出JSON?

此致 维塔利

5 个答案:

答案 0 :(得分:41)

tastypie cookbook开始,为了更改默认格式,您需要覆盖ModelResource上的determine_format()方法:

class MyResource(ModelResource):
    ....
    def determine_format(self, request):
        return 'application/json'

以上链接演示了确定输出格式的替代方法。

另外,我认为有效答案基本上不是“你不需要这个”。

修改

看来GregM的答案可能(我还没有测试过)最新的TastyPie版本,as per documentation将以下内容放在settings.py中会将序列化输出限制为json。

 TASTYPIE_DEFAULT_FORMATS = ['json']

答案 1 :(得分:10)

从tastypie 0.9.13开始,如果您不需要XML支持,可以通过在TASTYPIE_DEFAULT_FORMATS文件中将['json']设置为settings.py来全局禁用它。然后,请求应默认为JSON。

答案 2 :(得分:2)

我已经测试过将TASTYPIE_DEFAULT_FORMATS设置为['json'],但是当从浏览器查看API时,它不会阻止“抱歉尚未实现”消息。

能够通过在中间件中将“Accept”标头强制为“application / json”来消除警告:

class TastyJSONMiddleware(object):
    """
    A Django middleware to make the Tastypie API always output in JSON format
    instead of telling browsers that they haven't yet implemented text/html or
    whatever.

    WARNING: This includes a hardcoded url path for /api/.  This is not 'DRY'
    because it means you have to edit two places if you ever move your API
    path.
    """

    api_prefix = '/api/'

    def process_request(self, request):
        if request.path.startswith(self.api_prefix):
            request.META['HTTP_ACCEPT'] = 'application/json'

答案 3 :(得分:1)

要检查/测试您的REST API,请使用Rest客户端而不是浏览器,最好是知道如何打印JSON的浏览器。我使用Google Chrome的Postman插件。

如果你想在命令行中使用json:

curl https://api.twitter.com/1.1/search/tweets.json | python -m json.tool

答案 4 :(得分:1)

Tasytpie的默认设置为'application / json'。但是浏览器请求会覆盖它。

根据Tastypie,默认值被 请求标题 ACCEPT 覆盖,您的格式指定在 GET 即。 ?格式= JSON 。当您从浏览器发送请求时,如果您看到发送请求HTTP标头,则其类似于 -

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

application / xml 会覆盖Tastypie资源中的默认值。因此,您可以将浏览器标题设置为“application / json”(不好主意),或者只是在GET中指定。

如果您使用CURL访问相同的API网址,您将看到JSON输出,而不在GET中指定。