【问题标题】:sending post request in flask [duplicate]在烧瓶中发送帖子请求[重复]
【发布时间】:2017-09-22 04:31:27
【问题描述】:

我正在尝试在烧瓶中发送发布请求。

我想发送带有Content-Type: application/json 设置为标头的json 对象。

我正在使用 requests 模块执行此操作,如下所示:

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() 得到了一个意外的关键字参数 'json'

关于如何解决这个问题的任何建议?

【问题讨论】:

  • 通过data=json_string
  • 但是否设置了“Content-Type: application/json”?
  • 共有 3 个属性,headersparamdata。要设置像 content-type 这样的 headers 变量,您应该在 headers 属性中添加它

标签: python json firebase firebase-cloud-messaging


【解决方案1】:

先修复错误:

你需要改变这个:

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 的参数,但它接受名为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)
)

【讨论】:

  • 接缝效果很好
  • 我已经在我的答案中添加了一个完整的解决方案,看看!
  • "JSON_PARSING_ERROR: 位置 0 处的意外字符 (d)。\n"
  • 是的,我的错,毕竟需要json.dumps
  • 非常感谢您的帮助!
猜你喜欢
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
  • 2015-08-01
  • 1970-01-01
相关资源
最近更新 更多