【问题标题】:Django-tastypie. Output in JSON to the browser by defaultDjango-tastypie。默认以 JSON 格式输出到浏览器
【发布时间】:2012-01-28 18:44:42
【问题描述】:

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

问候, 活力

【问题讨论】:

    标签: django json tastypie


    【解决方案1】:

    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']
    

    【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 有一次我希望我可以给一件事不止一个 ☝️ rec。
    【解决方案3】:

    我已经测试了将 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'
    

    【讨论】:

      【解决方案4】:

      Tasytpie 的默认设置为“应用程序/json”。但这被浏览器请求覆盖。

      根据 Tastypie,默认值被 Request Header ACCEPTGET 中的格式规范覆盖,即。 ?format=json。当您从浏览器发送请求时,如果您看到发送的请求 HTTP 标头,它类似于 -

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

      application/xml 覆盖 Tastypie 资源中的默认值。因此,您可以将 Browser Header 设置为“application/json”(坏主意),或者您只需在 GET 中指定。

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

      【讨论】:

        【解决方案5】:

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

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

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

        【讨论】:

          猜你喜欢
          • 2018-01-11
          • 2015-06-09
          • 1970-01-01
          • 2020-05-05
          • 2014-08-10
          • 2016-10-11
          • 2012-07-19
          • 2012-01-29
          • 2010-09-07
          相关资源
          最近更新 更多