push notification of python

来源:互联网 发布:淘宝童装名字 编辑:程序博客网 时间:2024/06/10 23:03
import socket, ssl, json, struct# device token returned when the iPhone application# registers to receive alertsdeviceToken = ''thePayLoad = {     'aps': {          'alert':'New Images Ready',          'sound':'k1DiveAlarm.caf',          'badge':10,          },     'test_data': { 'foo': 'bar' },     }# Certificate issued by apple and converted to .pem format with openSSLtheCertfile = 'dev_cerkey_push.pem'#theHost = ( 'gateway.sandbox.push.apple.com', 2195 )#data = json.dumps( thePayLoad )# Clear out spaces in the device token and convert to hexdeviceToken = deviceToken.replace(' ','')byteToken = bytes.fromhex( deviceToken )theFormat = '!BH32sH%ds' % len(data)theNotification = struct.pack( theFormat, 0, 32, byteToken, len(data), data.encode() )# Create our connection using the certfile saved locallyssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = theCertfile )ssl_sock.connect( theHost )# Write out our datassl_sock.write( theNotification )# Close the connection -- apple would prefer that we keep# a connection open and push data as needed.ssl_sock.close()
代码来自: http://stackoverflow.com/questions/1052645/apple-pns-push-notification-services-sample-code
python2.7.1不支持bytes.fromhex,用
python3.2即可。
苹果官方文档中Provisioning and Development的Installing the SSL Certificate and Key on the Server部分的第3步不用管。
原创粉丝点击