Google App Engine:响应“Content-Length”标头始终为0

时间:2013-05-17 01:38:26

标签: python google-app-engine response webapp2 http-content-length

我遵循Google App Engine教程,我在向留言板课程中的响应对象添加内容时遇到了一些麻烦。

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

正如你所看到我试图用“Hello”填充内容正文但是它一直给我content-length = 0并且手动设置它似乎没有帮助所以我评论了它。我认为您可以安全地忽略带问候语的代码,但我在那里添加它以防它影响我做的任何事情。

1 个答案:

答案 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