【问题标题】:Google app engine json response as REST谷歌应用引擎 json 响应作为 REST
【发布时间】:2012-05-06 06:08:25
【问题描述】:

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

【问题讨论】:

  • ypu 是在 python2.7 还是 python2.5 上运行?
  • 我正在使用 Python 2.7 和 Google 应用引擎 sdk 1.6.4。

标签: python json google-app-engine


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢。 self.response.header['Content-Type'] 应该是 self.response.headers['Content-Type']。
  • 我已经改变了,现在我在问题的底部得到了一些错误提示。
  • 谢谢,我的错,我用的是同名的json。改变它,现在得到一个 json 响应。
猜你喜欢
  • 2013-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-11
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多