1

我遵循Google App Engine教程,在將內容添加到留言簿類中的響應對象時遇到了一些問題。Google App Engine:響應「內容長度」標頭始終爲0

class Guestbook(webapp2.RequestHandler): 
def post(self): 

    # We set the same parent key on the 'Greeting' to ensure each greeting 
    # is in the same entity group. Queries across the single entity group 
    # will be consistent. However, the write rate to a single entity group 
    # should be limited to ~1/second. 
    guestbook_name = self.request.get('guestbook_name', 
             DEFAULT_GUESTBOOK_NAME) 
    testvar = self.request.get('testvar', 
             DEFAULT_GUESTBOOK_NAME) 
    greeting = Greeting(parent=guestbook_key(guestbook_name)) 

    if users.get_current_user(): 
     greeting.author = users.get_current_user() 

    greeting.content = self.request.get('content') 
    greeting.info = 'DIDTHISWORK?' 
    greeting.put() 

    self.response.headers.add_header("Expires", 'Information here')  
    #self.response.set_status(200,'Is this working?!') 

    self.response.headers['Content-Type'] = 'text/plain' 
    #self.response.headers['Content-Length'] = '5' 
    self.response.out.write('Hello') 


    query_params = {'guestbook_name': guestbook_name} 
    self.redirect('/?' + urllib.urlencode(query_params)) 
    print type(self.response) 

使用Wireshark的這裏是應答包:

HTTP/1.1 302 Found 
Cache-Control: no-cache 
Expires: Information here 
Content-Type: text/plain 
Location: http://_______.appspot.com/?guestbook_name=default_guestbook 
Date: Fri, 17 May 2013 01:21:52 GMT 
Server: Google Frontend 
Content-Length: 0 

正如你看到的,我想用「你好」,以填補內容主體,但它一直給我內容長度= 0手動設置它似乎沒有幫助,所以我評論它。我認爲你可以安全地忽略問候的代碼,但是我將它添加到了那裏,以防它影響到我所做的任何事情。

回答

2

在將任何內容打印到頁面之前,您正在發送重定向,因此爲0。

self.redirect('/?' + urllib.urlencode(query_params)) # redirects 
print type(self.response)       # never executes 

如果你看一下Wireshark的捕獲,檢查出的響應代碼是302重定向和Location:報頭告訴瀏覽器重定向到。

HTTP/1.1 302 Found 
Location: http://_______.appspot.com/?guestbook_name=default_guestbook 
+0

非常感謝你!這工作 –

相關問題