苹果推送通知(APN)服务iOS端Python 2脚本

3
我已经配置了启用了苹果推送通知(APN)服务的iOS应用程序。我可以使用PHP和Python 3脚本向设备发送通知。我在本地服务器上测试了这两个脚本,并在本地机器上运行成功。但现在我需要用Python2编写脚本。
以下是我编写的脚本,当我运行它时,既没有通知到我的设备,也没有在命令行中出现错误。
import socket, ssl, json, struct
import binascii
import os

deviceToken = 'my_device_tocken_without_spaces' 

thePayLoad = {
     'aps': {
          'alert':'My first push notification!',
          'sound':'default'
          }
     }

theCertfile = 'ck3_2.pem'

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

data = json.dumps( thePayLoad )

theFormat = '!BH32sH%ds' % len(data)

theNotification = struct.pack( theFormat, 0, 32, deviceToken, 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()

我错过了什么?我怎样才能检查错误发生在哪里?

我在本地使用XAMPP运行了PHP脚本,在命令行中运行了Python脚本,因为我无法将Python与XAMPP设置好,我已经在这里发布了一个问题:

https://stackoverflow.com/questions/26930339/how-to-run-a-python-script-in-localhost-using-xampp-in-mac-os
3个回答

2
你可以考虑使用https://github.com/djacobs/PyAPNs,它包含了许多有用的功能,包括:
  • 错误处理
  • 支持增强消息格式以及自动重新发送之前发送失败的消息
  • 非阻塞ssl套接字连接,性能优异

0
你导入了binascii,但是忘记使用它了。 将令牌和JSON数据转换为字节数组,例如:
deviceToken = binascii.a2b_hex('my_device_tocken_without_spaces')

并且

data = json.dumps(thePayLoad, separators=(',', ':'), ensure_ascii=False).encode('utf-8')

0

是的,你说得对。代码几乎正确,并且在远程服务器上运行,但在本地机器上尝试运行时会出现错误。无论如何,在本地机器上运行时给出的错误是File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 333, in connect self._real_connect(addr, False) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 314, in _real_connect self.ca_certs, self.ciphers) ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib - AnujAroshA
你的证书文件路径是否正确?或者是否具有访问权限?我在这里找到了类似的错误 https://dev59.com/9G025IYBdhLWcg3wzZP2#6806097 - Gihan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接