pack(): char格式需要一个长度为1的字节对象。

时间:2021-08-10 10:19:47

I'm trying to send push notifications using the APNS from Python (I know there are lots of libraries that do just that, but this has pedagogic intentions).

我尝试用Python的APNS发送推送通知(我知道有很多这样的库,但是这有教育性的意图)。

I started using this script (source):

我开始使用这个脚本(源代码):

def send_push(token, payload):
    # Your certificate file
    cert = 'ck.pem'

    # APNS development server
    apns_address = ('gateway.sandbox.push.apple.com', 2195)

    # Use a socket to connect to APNS over SSL
    s = socket.socket()
    sock = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, certfile=cert)
    sock.connect(apns_address)

    # Generate a notification packet
    token = binascii.unhexlify(token)
    fmt = '!cH32sH{0:d}s'.format(len(payload))
    cmd = '\x00'
    message = struct.pack(fmt, cmd, len(token), token, len(payload), payload)
    sock.write(message)
    sock.close()

Which works, but Python 2.x only supports TSL until version 1. So I tried to run it using Python 3, and I get this error:

这是可行的,但是python2。x只支持TSL到版本1。所以我试着用python3运行它,我得到了这个错误

Traceback (most recent call last):
  File "push_notificator.py", line 52, in <module>
    send_notification(TOKEN, json.dumps(TEST_PAYLOAD))
  File "push_notificator.py", line 46, in send_push
    payload
struct.error: char format requires a bytes object of length 1

So it seems I must convert the payload to binary, but I'm really lost. This is the first time that I work with binary data on Python.

所以看起来我必须把有效载荷转换成二进制,但我真的输了。这是我第一次使用Python中的二进制数据。

1 个解决方案

#1


0  

In Python 3.x use:

Python 3。x使用:

bytes(payload, "utf-8")

Replace utf-8 with the necessary encoding.

用必要的编码替换utf-8。

Hope it helps.

希望它可以帮助。

#1


0  

In Python 3.x use:

Python 3。x使用:

bytes(payload, "utf-8")

Replace utf-8 with the necessary encoding.

用必要的编码替换utf-8。

Hope it helps.

希望它可以帮助。