使用Python的Apple推送通知服务

2 投票
2 回答
5408 浏览
提问于 2025-04-17 12:15

大家好,

我在使用下面的代码时遇到了一个关于APNs的问题。我找到了很多种源代码来实现这个服务。

import socket, ssl, json, struct import binascii

deviceToken = 'XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX' 

thePayLoad = {
     'aps': {
          'alert':'Hello world',
          'sound':'default',
          'badge':42,
          },
     'test_data': { 'foo': 'bar' },
     }

theCertfile = 'iphone_ck.pem'  

theHost = ( 'gateway.sandbox.push.apple.com', 2195 )

data = json.dumps( thePayLoad )

deviceToken = deviceToken.replace(' ','') 

byteToken = binascii.unhexlify(deviceToken)

theFormat = '!BH32sH%ds' % len(data) theNotification = struct.pack( theFormat, 0, 32, 

byteToken, len(data), data )

ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = theCertfile ) 

ssl_sock.connect( theHost )

ssl_sock.write( theNotification )

ssl_sock.close()

当我执行这段代码后,出现了下面的错误。每次我尝试在GitHub上使用PyAPNs或者在Google上使用APNWrapper时,最后都会遇到这个错误。所以,我决定自己来实现这个功能。

Traceback (most recent call last):
  File "testAPN.py", line 38, in <module>
    ssl_sock.connect( theHost )
  File "/usr/lib/python2.6/ssl.py", line 309, in connect
    self.do_handshake()
  File "/usr/lib/python2.6/ssl.py", line 293, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [Errno 1] _ssl.c:480: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 
alert handshake failure

有没有人能帮我解决这个错误,或者给我一些可能的方向,让我完成这个功能呢?

2 个回答

0

你还可以使用另一个库,

https://bitbucket.org/catwashere/pycat-apns

这样你就不用去纠结消息的结构或者连接的问题了。

0

我觉得你可以试试APNSWrapper这个模块来完成这个任务。

http://code.google.com/p/apns-python-wrapper/

这个模块使用起来简单,而且很常见。

撰写回答