【问题标题】:Google App Engine json post request bodyGoogle App Engine json 发布请求正文
【发布时间】:2011-07-02 06:07:31
【问题描述】:

每当我发送包含冒号“:”的字符串时,我都无法从 Google 应用引擎应用程序上的 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"}

为什么我不能得到只是身体的 hack? 谢谢!

【问题讨论】:

  • 您的实际代码是否省略了json_doesnt_work 定义中的单引号,或者这只是将代码复制到问题中的产物?

标签: python json google-app-engine post


【解决方案1】:

对于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)

【讨论】:

  • 您根本不应该在请求处理程序中使用print。为“更好”的建议 +1。
  • 如果它没有首先提出使用 print 的糟糕、破碎的解决方案,我会赞成这个答案。
  • 很好的答案,谢谢。后来我确实尝试使用 response.out.write 并且它有效,但我不知道为什么 print 不起作用。
  • 那些打印语句是 在 WSGI 应用程序之外的——它们在 CGI 示例中。你永远不应该在 WSGI 应用程序中使用 print,因为应用程序本身负责输出结果(包括标题)。
猜你喜欢
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 2018-05-18
  • 2013-06-12
  • 1970-01-01
相关资源
最近更新 更多