【问题标题】:How to properly output JSON with app engine Python webapp2?如何使用应用引擎 Python webapp2 正确输出 JSON?
【发布时间】:2012-09-21 19:05:57
【问题描述】:

现在我正在这样做:

self.response.headers['Content-Type'] = 'application/json'
self.response.out.write('{"success": "some var", "payload": "some var"}')

有没有更好的方法来使用一些库?

【问题讨论】:

标签: json google-app-engine webapp2


【解决方案1】:

是的,您应该使用 Python 2.7 支持的json library

import json

self.response.headers['Content-Type'] = 'application/json'   
obj = {
  'success': 'some var', 
  'payload': 'some var',
} 
self.response.out.write(json.dumps(obj))

【讨论】:

  • 噢!我一直在使用self.response.headers['Content-Type:'] = 'application/json' 并拉扯我的细线……头发。不小心加了一个冒号。
【解决方案2】:

webapp2 为 json 模块提供了一个方便的包装器:如果可用,它将使用 simplejson,或者如果可用,则使用 Python >= 2.6 的 json 模块,并将 App Engine 上的 django.utils.simplejson 模块作为最后一个资源。

http://webapp2.readthedocs.io/en/latest/api/webapp2_extras/json.html

from webapp2_extras import json

self.response.content_type = 'application/json'
obj = {
    'success': 'some var', 
    'payload': 'some var',
  } 
self.response.write(json.encode(obj))

【讨论】:

    【解决方案3】:

    python本身有一个json module,它会确保你的JSON格式正确,手写的JSON更容易出错。

    import json
    self.response.headers['Content-Type'] = 'application/json'   
    json.dump({"success":somevar,"payload":someothervar},self.response.out)
    

    【讨论】:

    • 我可能是错的,但我怀疑这是否真的有效。为什么要将self.response.out 作为参数传递给dump 函数?
    • 确实如此。 self.response.out 是一个流,而 dump() 将一个流作为它的第二个参数。 (也许你对 dump() 和 dumps() 的区别感到困惑?)
    【解决方案4】:

    我通常是这样使用的:

    class JsonEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, datetime):
                return obj.isoformat()
            elif isinstance(obj, ndb.Key):
                return obj.urlsafe()
    
            return json.JSONEncoder.default(self, obj)
    
    class BaseRequestHandler(webapp2.RequestHandler):
        def json_response(self, data, status=200):
            self.response.headers['Content-Type'] = 'application/json'
            self.response.status_int = status
            self.response.write(json.dumps(data, cls=JsonEncoder))
    
    class APIHandler(BaseRequestHandler):
        def get_product(self): 
            product = Product.get(id=1)
            if product:
                jpro = product.to_dict()
                self.json_response(jpro)
            else:
                self.json_response({'msg': 'product not found'}, status=404)
    

    【讨论】:

      【解决方案5】:
      import json
      import webapp2
      
      def jsonify(**kwargs):
          response = webapp2.Response(content_type="application/json")
          json.dump(kwargs, response.out)
          return response
      

      你想返回一个json响应的每个地方...

      return jsonify(arg1='val1', arg2='val2')
      

      return jsonify({ 'arg1': 'val1', 'arg2': 'val2' })
      

      【讨论】:

        猜你喜欢
        • 2012-06-26
        • 2017-07-07
        • 2012-12-09
        • 1970-01-01
        • 2015-11-23
        • 1970-01-01
        • 1970-01-01
        • 2012-07-10
        • 2013-05-12
        相关资源
        最近更新 更多