【发布时间】: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
现在我正在这样做:
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write('{"success": "some var", "payload": "some var"}')
有没有更好的方法来使用一些库?
【问题讨论】:
标签: json google-app-engine webapp2
是的,您应该使用 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' 并拉扯我的细线……头发。不小心加了一个冒号。
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))
【讨论】:
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 函数?
我通常是这样使用的:
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)
【讨论】:
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' })
【讨论】: