2016-02-26 66 views
2

我想發送一個從client.py創建的python字典到我的webservice,讓webservice對數據做些什麼,然後返回一個布爾值給client.py。這是代碼我到目前爲止對服務器和客戶端:如何從燒瓶發送和接收數據?

服務器端(裏面webservice.py):

from flask import Flask 
from flask import request 
import json 

app = Flask(__name__) 

@app.route('/determine_escalation',methods = ['POST']) 
def determine_escalation(): 
    jsondata = request.form['jsondata'] 
    data = json.loads(jsondata) 

    #stuff happens here that involves data to obtain a result 

    result = {'escalate':'True'} 
    return json.dumps(result) 


if __name__ == '__main__': 
    app.run(debug=True) 

客戶端(內client.py):

import sys 
import json 
import requests 

conv = [{'input': 'hi', 'topic': 'Greeting'}] 
s = json.dumps(conv) 
res = requests.post("http://127.0.0.1:5000/determine_escalation",data=s) 
print res.text 

但是,當我打印出res.text,我得到這個:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> 
<title>400 Bad Request</title> 
<h1>Bad Request</h1> 
<p>The browser (or proxy) sent a request that this server could not understand.</p> 

我在做什麼錯,我該如何解決這個問題?新的Flask和JSON的東西,所以任何幫助表示讚賞。

回答

5

OK - 一些問題在這裏:

首先,你可以使用requests.get_json()在服務器端檢索您的JSON數據:

from flask import Flask 
from flask import request 
import json 

app = Flask(__name__) 

@app.route('/determine_escalation/', methods = ['POST']) 
def determine_escalation(): 
    jsondata = request.get_json() 
    data = json.loads(jsondata) 

    #stuff happens here that involves data to obtain a result 

    result = {'escalate': True} 
    return json.dumps(result) 


if __name__ == '__main__': 
    app.run(debug=True) 

此外,當你把你的數據在一起,而不是使用「數據= S」發送請求,用「JSON = S」:

import sys 
import json 
import requests 

conv = [{'input': 'hi', 'topic': 'Greeting'}] 
s = json.dumps(conv) 
res = requests.post("http://127.0.0.1:5000/determine_escalation/", json=s).json() 
print(res['escalate']) 

請注意,我在URL的末尾添加結尾的斜槓 - 這僅僅是很好的做法: - )

我還引入了MarcelK的建議更改 - 從布爾值'True'(服務器端)刪除引號並使用.json()解析客戶端的響應 - 這些都是很好的建議。

我測試過這個修訂版(並重新修訂版),它工作正常。

+2

要使其完成,您還可以將.json()附加到request.post(...)以直接解析json。在determine_escalation()中,當結果字典包含布爾值True而不是字符串'True'時,所有內容都應按預期工作;) – MarcelK

+0

非常感謝,Neil!對於那些可能會覺得這很有用的用戶:通過執行sudo pip安裝請求 - 升級來升級您的請求模塊。否則,請求將不接受json參數.post – ilikecats

+0

自[請求2.4.2](http://docs.python-requests.org/en/master/community/updates/#id16)開始支持json參數, – MarcelK