2013-02-20 66 views
14

我无法通过bottle.py阅读POST请求。阅读POST body with bottle.py

发送的请求在其正文中包含一些文本。您可以在第29行看到它是如何制作的:https://github.com/kinetica/tries-on.js/blob/master/lib/game.js

您还可以在第4行上看到如何在基于node的客户端上读取它:https://github.com/kinetica/tries-on.js/blob/master/masterClient.js

但是,我还没有能够模仿我的bottle.py客户端上的这种行为。 docs表示我可以用类似文件的对象读取原始文件,但我无法使用request.body上的for循环获取数据,也无法使用request.bodyreadlines方法获取数据。

我在用@route('/', method='POST')装饰的功能中处理请求,请求正确到达。

在此先感谢。


编辑:

完整的脚本是:

from bottle import route, run, request 

@route('/', method='POST') 
def index(): 
    for l in request.body: 
     print l 
    print request.body.readlines() 

run(host='localhost', port=8080, debug=True) 
+0

我认为这是需要倒带'StringIO'对象,但它没有必要。你可以将Python函数添加到你的问题吗? – 2013-02-20 20:44:12

+0

当然。我已经更新了答案。谢谢,@ A.Rodas – 2013-02-20 20:57:51

+0

您如何知道请求正确到达?这里显示的代码的输出和/或回溯是什么? – 2013-02-20 22:15:46

回答

13

你尝试简单postdata = request.body.read()

下面的例子显示使用request.body.read()

还将输出到日志文件(而不是客户端)身体的原始内容读取原始格式发布的数据。

为了显示表单属性的访问权限,我添加了返回“姓名”和“姓氏”给客户端。

为了进行测试,我用卷曲客户端的命令行:

$ curl -X POST -F name=jan -F surname=vlcinsky http://localhost:8080 

这对我的作品的代码:

from bottle import run, request, post 

@post('/') 
def index(): 
    postdata = request.body.read() 
    print postdata #this goes to log file only, not to client 
    name = request.forms.get("name") 
    surname = request.forms.get("surname") 
    return "Hi {name} {surname}".format(name=name, surname=surname) 

run(host='localhost', port=8080, debug=True) 
+0

POST变得很复杂 – 2014-06-03 07:12:37