2017-04-25 142 views
1

我正嘗試在燒瓶中發送發佈請求。在燒瓶中發送發佈請求

我想發送帶有Content-Type: application/json設置爲標頭的json對象。

我與請求如下這樣模塊:

json_fcm_data = {"data":[{'key':app.config['FCM_APP_TOKEN']}], "notification":[{'title':'Wyslalem cos z serwera', 'body':'Me'}], "to":User.query.filter_by(id=2).first().fcm_token} 
json_string = json.dumps(json_fcm_data) 
print json_string 
res = requests.post('https://fcm.googleapis.com/fcm/send', json=json_string) 

但是這給了我:

TypeError: request() got an unexpected keyword argument 'json'

就如何解決這一問題有何意見?

+0

通'數據= json_string' –

+0

但不要把它設置「內容類型:應用程序/ JSON」? – demoo

+1

有3個屬性,'header','param'和'data'。要設置標題變量像'content-type',你應該在標題 –

回答

2

首先修復錯誤:

您需要更改此設置:

res = requests.post('https://fcm.googleapis.com/fcm/send', json=json_string) 

這樣:

res = requests.post('https://fcm.googleapis.com/fcm/send', data=json_string) 

錯誤你得到指出requests.post不能接受一個名爲json的參數,但它接受關鍵字arg命名爲data,它可以是json格式。

添加您的標題:

如果您要發送自定義頁眉與requests模塊,你可以按如下做到這一點:

headers = {'your_header_title': 'your_header'} 
# In you case: headers = {'content-type': 'application/json'} 
r = requests.post("your_url", headers=headers, data=your_data) 

總結了一切:

你需要修正你的json格式。一個完整的解決方案將是:

json_data = {"data":{ 
       'key':app.config['FCM_APP_TOKEN'] 
       }, 
      "notification":{ 
       'title':'Wyslalem cos z serwera', 
       'body':'Me' 
       }, 
      "to":User.query.filter_by(id=2).first().fcm_token 
      } 

headers = {'content-type': 'application/json'} 
r = requests.post('https://fcm.googleapis.com/fcm/send', 
        headers=headers, 
        data=json.dumps(json_data)) 
+0

它接縫它的工作<3謝謝!你能檢查我是否正確地做了JSON對象嗎?我希望得到的東西是這樣的: { 「數據」: { 「關鍵」: 「值」 } 「通知」: { 「稱號」: 「你好」, 「體」:「確定「 }, 」to「:」token「 } – demoo

+1

我在回答中添加了一個完整的解決方案,看看! –

+0

「JSON_PARSING_ERROR:意外的字符(d)在位置0. \ n」 – demoo