2011-02-22 80 views
4

我不能從谷歌應用程序引擎的應用POST請求讀取身體,每當我發送包含字符串冒號「:」谷歌App Engine的JSON 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"} 

爲什麼黑客我不能只是身體? 謝謝!

+0

請問您的實際代碼省略結束單引號中json_doesnt_work`的'的定義或爲那只是將代碼隱藏到問題中的工件? – 2011-02-22 19:53:00

回答

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) 
+8

你永遠不應該在請求處理程序中使用`print`。 +1爲「更好」的建議。 – geoffspear 2011-02-22 20:38:29