2

如何将页面响应为 json 页面?下面的代码是否正确?

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import json

class JsonPage(webapp.RequestHandler):
    def get(self):
        self.response.header['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]))

application = webapp.WSGIApplication([('json', JsonPage)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()

我收到以下错误消息:

HTTP request sent, awaiting response... 404 Not Found
2012-05-06 14:10:01 ERROR 404: Not Found.

对代码进行一些更改后,出现以下错误,似乎在 json 模块中找不到转储对象:

<pre>Traceback (most recent call last):
  File &quot;/opt/google_appengine/google/appengine/ext/webapp/_webapp25.py&quot;, line 701, in __call__
    handler.get(*groups)
  File &quot;/home/kelvin/workspace/cloudnuts/json.py&quot;, line 8, in get
    self.response.out.write(json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]))
AttributeError: 'module' object has no attribute 'dumps'
</pre>
4

1 回答 1

1

您可能应该将代码更改为:

application = webapp.WSGIApplication([('/json', JsonPage)], debug=True)

至于你的 json 问题,你有本地文件名为 json.py 吗?它将覆盖 json 包导入。

于 2012-05-06T06:12:23.550 回答