【问题标题】:Reading POST body with bottle.py使用 bottle.py 阅读 POST 正文
【发布时间】:2013-02-05 23:42:12
【问题描述】:

我无法读取带有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)

【问题讨论】:

  • 我认为需要倒带 StringIO 对象,但没有必要。您能否将 Python 函数添加到您的问题中?
  • 当然。我已经更新了答案。谢谢,@A.Rodas
  • 您如何知道请求正确到达?您在此处显示的代码的输出和/或回溯是什么?
  • 每次我提出请求时,Bottle 都会在控制台上打印 200 个状态代码。我还使用 Eclipse/PyDev 调试了应用程序,并且在断点处正确执行中断。
  • 那么您是说您没有收到任何错误,而request.body 似乎是空的? (所以for 循环什么也不打印,而你的第二个print 语句打印[]?)

标签: python post python-2.7 bottle


【解决方案1】:

你试过简单的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)

【讨论】:

    【解决方案2】:

    用于处理 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)
    

    【讨论】:

    猜你喜欢
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2021-02-02
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2015-11-11
    相关资源
    最近更新 更多