tornado中requesthandler收到的json数据解析出错,请问如何解析post请求中的json格式数据
写了一个简单的tornado程序,目的接受脚本post的json数据,解析并response,返回json数据。
client脚本如下:
# -*- coding:utf-8 -*-
import urllib
import urllib2
import json
url='http://127.0.0.1:8888'
values ={'user':'a','passwd':'b'}
jdata = json.dumps(values)
req = urllib2.Request(url)
req.add_data(jdata)
print req.headers
response = urllib2.urlopen(req)
tornado程序如下:
# -*- coding:utf-8 -*-
import tornado.ioloop
import tornado.web
import tornado.httpserver
from tornado.options import define, options
import json
define("port",default=8888,help='run a test')
class MainHandler(tornado.web.RequestHandler):
def get(self):
info={'user':'leno'}
jinfo=json.dumps(info)
self.write(jinfo)
def post(self,*args,**kwargs):
print 'post message'
print self.request.remote_ip
print self.request.body_arguments
user=self.get_body_argument('user')
pw=self.get_body_argument('passwd')
print user
jdata=json.loads(user)
print jdata
data=json.loads(jdata)
def set_default_headers(self):
self.set_header('Content-type','application/json;charset=utf-8')
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
在get_body_argument处出错:Missing argument user,
print self.request.body_arguments则显示{'{"passwd": "b", "user": "a"}': ['']}
在client处却正常,请问如何解决?谢谢!
性感的云吞
9 years, 4 months ago
Answers
最后发现不能用get_argumentm,采用的是如下:
from tornado.escape import json_decode
def post(self,*args,**kwargs):
print 'post message'
print self.request.remote_ip
print self.request.body_arguments
data=json_decode(self.request.body)
user=data['user']
pw=data['passwd']
print user,pw
jdata=json.dumps(data)
print jdata
self.write(jdata)
开始看见别人ajax用get_argument,以为能直接解析json,被误导了。中间拿到request的body,自己解析后就行了,还是感谢rsj217的回答
WINNER
answered 9 years, 4 months ago