谷歌应用程序引擎json响应为REST

时间:2012-05-06 06:08:25

标签: python json google-app-engine

如何将页面作为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>

1 个答案:

答案 0 :(得分:1)

您应该将代码更改为:

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

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