python - 用 bottle.py 读取 POST 正文

标签 python post python-2.7 bottle

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

发送的请求正文中有一些文本。你可以在第 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)

最佳答案

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

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

以原始格式读取发布的数据

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

为了显示对表单属性的访问,我添加了向客户端返回“name”和“surname”。

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

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

关于python - 用 bottle.py 读取 POST 正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14988887/

相关文章:

python - 将财政周数据汇总为 pandas 中的月度总和

PHP:如何从 $.post 请求返回数据作为响应?

PHP - 从函数返回数组

python : Iterate through list and sublists and match first elements and do some more manipulations

python-2.7 - 同一图上的 Python 并排箱线图

python - 如何在cygwin中运行的python中拦截ctrl + c命令

python - "no python application found"uWSGI + nginx + Ubuntu 13

python - 目录大小和扩展

python - 如何在Python中有效计算(稀疏)位矩阵上的矩阵乘积

android - 在 Android 中使用 DataOutputStream 在 POST 正文中发送特殊字符 (ë ä ï)