在appengine中解析json格式化的请求

时间:2012-08-23 11:57:38

标签: python google-app-engine

最近正在开发一个appengine应用程序。我想解析请求中包含的json数据到应用程序。如何使用requesthandler类的请求对象来实现此目的?

下面是代码片段,展示了我想要实现的目标:

import cgi
import webapp2
import datamethods

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

class adduser(webapp2.RequestHandler):
    def get(self):
        # Get the phone number from json data in request.
        userphone = self.request.get("phone")
        # Get the name from json data in request.
        name = self.request.get("name")


app = webapp2.WSGIApplication([
  ('/adduser', adduser),
  ('/sign', updatestatus),
  ('/login',login)
], debug=True)


def main():
    run_wsgi_app(app)

if __name__ == "__main__":
    main() 

2 个答案:

答案 0 :(得分:17)

您必须在对象中解析传入的json字符串。在此之后,您可以访问属性。

import json   # Now you can import json instead of simplejson
....
jsonstring = self.request.body
jsonobject = json.loads(jsonstring)

答案 1 :(得分:0)

import cgi
import webapp2
import datamethods

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

class adduser(webapp2.RequestHandler):
    def get(self):
        items = [] 
        response = { }

        userphone = self.request.get("phone") 
        name = self.request.get("name")

        items.append({'userphone': userphone , 'name':name})
        response['userInformation'] = items
        return response #return json data


app = webapp2.WSGIApplication([
  ('/adduser', adduser),
  ('/sign', updatestatus),
  ('/login',login)
], debug=True)


def main():
    run_wsgi_app(app)

if __name__ == "__main__":
    main()