20

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

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.

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.

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.

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

Thanks in advance.


EDIT:

The complete script is:

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

2 回答 2

19

你试过简单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)
于 2014-04-20T21:30:41.453 回答
6

用于处理 POST 数据的简单脚本。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 数据 POST 到上述脚本的脚本:

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)
于 2018-11-05T08:06:57.067 回答