Google App Engine json POST 请求体
我在谷歌应用引擎的应用中,发送包含冒号“:”的字符串时,无法读取POST请求的主体。
这是我的请求处理类:
class MessageSync(webapp.RequestHandler):
def post(self):
print self.request.body
这是我的测试脚本:
import httplib2
json_works = '{"works"}'
json_doesnt_work = '{"sux": "test"}'
h = httplib2.Http()
resp, content = h.request('http://localhost:8080/msg',
'POST',
json_works ,
headers={'Content-Type': 'application/json'})
print content
如果我使用变量json_works,请求主体会被打印出来,但如果我使用json_doest_work,就不会在控制台上得到任何响应。除非我打印整个请求对象,这样我能看到:
POST /msg
Content-Length: 134
Content-Type: application/json
Host: localhost:8080
User-Agent: Python-httplib2/$Rev$
{"sux": "test"}
为什么我就是无法获取主体呢?谢谢!
1 个回答
11
在json_doesnt_work
的情况下,print
函数把self.request.body
当作一个Response header
来设置,因为它的形式是{key:value}
这样的参数。
{'status': '200', 'content-length': '0',
'expires': 'Fri, 01 Jan 1990 00:00:00 GMT',
'server': 'Development/1.0',
'cache-control': 'no-cache',
'date': 'Tue, 22 Feb 2011 21:54:15 GMT',
'{"sux"': '"test"}', <=== HERE!
'content-type': 'text/html; charset=utf-8'
}
你应该这样修改你的处理程序:
class MessageSync(webapp.RequestHandler):
def post(self):
print ''
print self.request.body
或者更好一些
class MessageSync(webapp.RequestHandler):
def post(self):
self.response.headers['Content-Type'] = "text/plain"
self.response.out.write(self.request.body)