Mar*_*oll 16 python post bottle python-2.7
我在阅读POST请求时遇到问题bottle.py.
发送的请求在其正文中有一些文本.您可以在第29行看到它是如何制作的:https://github.com/kinetica/tries-on.js/blob/master/lib/game.js.
您还可以node在第4行看到它在基于客户端的客户端上的读取方式:https://github.com/kinetica/tries-on.js/blob/master/masterClient.js.
但是,我无法在bottle.py基于客户端的客户端上模仿此行为.该文档说,我可以用一个类似文件的对象读取原始的身体,但也使用了上环,我不能得到数据request.body,也不能使用request.body的readlines方法.
我正在用装饰的函数处理请求@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)
Run Code Online (Sandbox Code Playgroud)
Jan*_*sky 16
你尝试过简单postdata = request.body.read()吗?
以下示例显示了使用原始格式读取发布数据 request.body.read()
它还会打印到日志文件(而不是客户端)的正文内容.
为了显示表单属性的访问,我添加了返回"name"和"surname"给客户端.
为了测试,我在命令行中使用了curl客户端:
$ curl -X POST -F name=jan -F surname=vlcinsky http://localhost:8080
Run Code Online (Sandbox Code Playgroud)
适用于我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
处理 POSTed 数据的简单脚本。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)
Run Code Online (Sandbox Code Playgroud)
用于将 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)
Run Code Online (Sandbox Code Playgroud)