38

Right now I am currently just doing this:

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

Is there a better way to do it using some library?

4

5 回答 5

60

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

import json

self.response.headers['Content-Type'] = 'application/json'   
obj = {
  'success': 'some var', 
  'payload': 'some var',
} 
self.response.out.write(json.dumps(obj))
于 2012-09-30T20:30:57.293 回答
31

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))
于 2013-03-12T23:24:04.323 回答
13

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

import json
self.response.headers['Content-Type'] = 'application/json'   
json.dump({"success":somevar,"payload":someothervar},self.response.out)
于 2012-09-30T20:32:11.240 回答
3

我通常这样使用:

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)
于 2017-03-08T02:49:49.610 回答
1
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' })
于 2016-02-28T00:25:04.143 回答