from bson.json_util import dumps
def json_response(response):
return {"response":dumps(response,ensure_ascii=False).encode("utf8")
,"headers":{"Content-type":"text/json"}}
这个问题让我抓狂。它随机返回错误,我找不到解决方案。
/core/handlers/wsgi.py", line 38, in __call__,
output = lookup_view(req),
File "auth/decorator.py", line 8, in wrap,
return fn(req,*args,**kwargs),
File "auth/decorator.py", line 21, in wrap,
return fn(req,*args,**kwargs),
File "contrib/admin/views.py", line 67, in submit_base_premission,
return json_response({"baseperm":baseperm,"Meta":{"gmsg":u"...","type":201}}),
File "render/render_response.py", line 85, in json_response,
return {"response":dumps(response,ensure_ascii=False).encode("utf8"),
File "/usr/local/lib/python2.7/dist-packages/bson/json_util.py", line 116, in dumps,
return json.dumps(_json_convert(obj), *args, **kwargs),
File "/usr/lib/python2.7/json/__init__.py", line 238, in dumps, referer:
**kw).encode(obj),
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode,
chunks = self.iterencode(o, _one_shot=True),
File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode,
return _iterencode(o, 0),
File "/usr/lib/python2.7/json/encoder.py", line 178, in default,
raise TypeError(repr(o) + " is not JSON serializable"),
TypeError: ObjectId('51f7dcee95113b7a48e974fe') is not JSON serializable,
baseperm
是一个 pymongo Cursor
,它随机返回此错误,这就是我遇到问题的地方。似乎它objectid
有时不会检测到并且不会将其转换为str
因此 json 在转储时引发错误。