2017-04-25 145 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