用bottle.py读取POST正文 [英] Reading POST body with bottle.py

查看:248
本文介绍了用bottle.py读取POST正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用bottle.py读取POST请求时遇到问题.

I am having trouble reading a POST request with bottle.py.

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

The request sent has some text in its body. You can see how it's made here on line 29: https://github.com/kinetica/tries-on.js/blob/master/lib/game.js.

您还可以在第4行上的基于node的客户端上查看其读取方式:

You can also see how it's read on a node-based client here on line 4: https://github.com/kinetica/tries-on.js/blob/master/masterClient.js.

但是,我无法在基于bottle.py的客户端上模仿此行为. 文档说,我可以使用类似于文件的对象,但是我既无法使用request.body上的for循环也无法使用request.bodyreadlines方法来获取数据.

However, I haven't been able to mimic this behavior on my bottle.py-based client. The docs say that I can read the raw body with a file-like object, but I can't get the data neither using a for loop on request.body, nor using request.body's readlines method.

我正在使用装饰有@route('/', method='POST')的函数处理请求,并且请求可以正确到达.

I'm handling the request in a function decorated with @route('/', method='POST'), and requests arrive correctly.

提前谢谢.

完整的脚本是:

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)

推荐答案

您尝试过简单的postdata = request.body.read()吗?

以下示例显示了使用request.body.read()

它还将打印正文的原始内容到日志文件(而不是到客户端).

It also prints to the log file (not to the client) raw content of body.

为了显示对表单属性的访问,我向客户端添加了返回的名称"和姓".

To show accessing of form properties, I added returning "name" and "surname" to the client.

为了进行测试,我从命令行使用curl客户端:

For testing, I used curl client from command line:

$ 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)

这篇关于用bottle.py读取POST正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆