python使用pyapns进行ios推送消息

2014/01/17

Pyapns 提供了通用的Apple Push Notification Service (APNS)。该解决方案使用了开源的Twisted server,支持原生的Python和Ruby API。

功能

XML-RPC Based, works with any client in any language
Native Python API with Django and Pylons support
Native Ruby API with Rails/Rack support
Scalable, fast and easy to distribute behind a proxy
Based on Twisted
Multi-application and dual environment support
Simplified feedback interface

pyapns项目github开源地址:https://github.com/samuraisam/pyapns

安装

(使用pip或easy_install安装。会安装Twisted框架)

pip install pyapns 或者使用 easy_install pyapns

启动twisted

#linux
twistd -r epoll web --class=pyapns.server.APNSServer --port=7077

#mac os
twistd -r kqueue web --class=pyapns.server.APNSServer --port=7077

新建push.py文件输入下面内容

#!/usr/bin/python
# -*- coding: utf-8 -*
# Filename: push.py

from pyapns import configure, provision, notify

tokens = ["token1" ,
          "token2"]

notifications = [
    {'aps' :{'alert': 'Hello token 1', 'badge': 0, 'sound': 'flynn.caf'}},
]

configure({'HOST': 'http://localhost:7077/'})
provision('myapp', open('developent.pem').read(), 'sandbox')
notify('myapp', tokens, notifications)

pyapns推送消息需要一个pem格式的证书文件,跟Parse里要求一个.p12文件不同啊。我看看怎么搞到这文件。从苹果下载的证书是.cer格式的,在苹果的KeyChain程序中,选择导出,可是,只能选择导出成.cer和.p12文件,.pem的选项被禁用了,好桑心。通过搜索export pem from keychain找到Creating .pem file for APNS?,简单说,就是在KeyChain里导出.p12格式的,再通过下面的命令转换成.pem的。搞定。

openssl pkcs12 -in Development.p12 -out developent.pem -nodes -clcerts

python push.py

推送成功

done.