使用 bottle.py 读取 POST 请求体

21 投票
2 回答
39980 浏览
提问于 2025-04-17 16:32

我在用 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 客户端中无法模拟这种行为。文档说我可以用一个像文件一样的对象来读取原始内容,但我无论是用 for 循环遍历 request.body,还是用 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)

2 个回答

7

这是一个简单的脚本,用来处理通过POST方式发送的数据。发送的数据会在终端显示出来,然后再返回给客户端:

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

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

下面的例子展示了如何使用 request.body.read() 来读取以原始格式发送的数据。

它还会把请求体的原始内容打印到日志文件中(而不是发送给客户端)。

为了展示如何访问表单的属性,我添加了返回“名字”和“姓氏”给客户端的功能。

在测试时,我使用了命令行中的 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)

撰写回答