簡體   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