繁体   English   中英

用bottle.py读取POST主体

[英]Reading POST body with bottle.py

我在使用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的客户端上模仿这种行为。 文档说我可以用类似文件的对象读取原始主体,但我无法在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()以原始格式读取发布的数据

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

为了显示表单属性的访问,我添加了返回“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)

用于处理POSTed数据的简单脚本。 发布的数据写在终端中并返回给客户端:

from bottle import get, post, run, request
import sys

@get('/api')
def hello():
    return "This is api page for processing POSTed messages"

@post('/api')
def api():
    print(request.body.getvalue().decode('utf-8'), file=sys.stdout)
    return request.body

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

将json数据发布到上面脚本的脚本:

import requests
payload = "{\"name\":\"John\",\"age\":30,\"cars\":[ \"Ford\", \"BMW\",\"Fiat\"]}"
url = "localhost:8080/api"
headers = {
  'content-type': "application/json",
  'cache-control': "no-cache"
  }
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM