-3

我想在(带有pycurl的python)中使用这个cURL命令:

curl -X POST --header "Authorization: key=AAAAWuduLSU:APA91bEStixxx" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d '{"to" : "fC6xEWZwcu0:APA91xxx",  "priority" : "high",  "notification" : {    "body" : "Background Message",    "title" : "BG Title", "sound" : "default"},  "data" : {    "title" : "FG Title",    "message" : "Foreground Message"  }}'

我的源代码是这样的

import pycurl
import re
import io
import json
import requests

data = {"to" : "fC6xEWZwcu0:APA91xxx",  "priority" : "high",  "notification" : {    "body" : "Background Message",    "title" : "BG Title", "sound" : "sound.mp3"},  "data" : {    "title" : "FG Title",    "message" : "Foreground Message"  }}

buffer = io.BytesIO()
c = pycurl.Curl()

c.setopt(c.URL, 'https://fcm.googleapis.com/fcm/send')
c.setopt(c.POST, True)
c.setopt(c.SSL_VERIFYPEER, False)

c.setopt(pycurl.HTTPHEADER, [
    'Content-type:application/json charset=utf-8',
    'Content-Length:0'
    'Authorization: Basic key=AAAAWuduLSU:APA91bEStixxx'
])

c.setopt(c.WRITEDATA, buffer)

'''
c.setopt(pycurl.HTTPBODY, [
    'test:test'

])
'''

print(buffer)
# c.setopt(c.HEADERFUNCTION, header_function)

c.perform()

print('\n\nStatus: %d' % c.getinfo(c.RESPONSE_CODE))
print('TOTAL_TIME: %f' % c.getinfo(c.TOTAL_TIME))

c.close()
body = buffer.getvalue()

print(body)
4

1 回答 1

0

有请求时无需在 Python 中使用 curl!

import requests
import json

post_data = {"to" : "fC6xEWZwcu0:APA91xxx",
             "priority" : "high",
             "notification": {"body": "Background Message",
                              "title": "BG Title",
                              "sound": "sound.mp3"},
             "data": {"title": "FG Title",
                      "message": "Foreground Message"}}

header_data = {'Authorization': 'key=AAAAWuduLSU:APA91bEStixxx',
               'Content-Length': '0',
               'Content-type': 'application/json'}

r = requests.post('https://fcm.googleapis.com/fcm/send',
                   data = json.dumps(post_data),
                   headers=header_data)

print('\n\nStatus: %d'.format(r.status_code))
print('TOTAL_TIME: %f'.format(r.elapsed.total_seconds()))
print(r.text)

尚未对此进行测试,但它应该使您走上正轨。我还建议查看请求模块文档以获取更多信息:-)

于 2018-04-08T09:37:47.440 回答