Skip to main content
 首页 » 编程设计

python之谷歌应用引擎 json 响应作为 REST

2025年05月04日10lautakyan007

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

请您参考如下方法:

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

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

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