Coder Social home page Coder Social logo

jpush / jpush-api-python-client Goto Github PK

View Code? Open in Web Editor NEW
208.0 30.0 88.0 195 KB

JPush's officially supported Python client library for accessing JPush APIs. 极光推送官方支持的 Python 版本服务器端 SDK。

Home Page: https://docs.jiguang.cn

Python 100.00%
jpush python sdk

jpush-api-python-client's Introduction

JPush API Python Client

概述

这是 JPush REST API 的 Python 版本封装开发包,是由极光推送官方提供的,一般支持最新的 API 功能。

对应的 REST API 文档:https://docs.jiguang.cn/jpush/server/push/server_overview/

兼容版本

  • Python 2.7
  • Python 3

环境配置

pip 方式:

sudo pip install jpush

easy_install 方式:

sudo easy_install jpush

使用源码方式:

sudo python setup.py install

代码样例

代码样例在 jpush-api-python-client 中的 examples 文件夹中,点击查看所有 examples

以下片断来自项目代码里的文件:jpush-api-python-client 中的 examples/push_examples 目录下的 example_all.py

这个样例演示了消息推送,日志设置,异常处理。

_jpush = jpush.JPush(app_key, master_secret)
push = _jpush.create_push()
# if you set the logging level to "DEBUG",it will show the debug logging.
_jpush.set_logging("DEBUG")
push.audience = jpush.all_
push.notification = jpush.notification(alert="hello python jpush api")
push.platform = jpush.all_
try:
    response=push.send()
except common.Unauthorized:
    raise common.Unauthorized("Unauthorized")
except common.APIConnectionException:
    raise common.APIConnectionException("conn error")
except common.JPushFailure:
    print ("JPushFailure")
except:
    print ("Exception")

日志说明

logging level 默认的是 WARNING ,为了方便调试建议设置为 DEBUG 设置方法为:

_jpush.set_logging("DEBUG")

异常说明

  • Unauthorized

    • AppKey,Master Secret 错误,验证失败必须改正。
  • APIConnectionException

    • 包含错误的信息:比如超时,无网络等情况。
  • JPushFailure

    • 请求出错,参考业务返回码。

HTTP 状态码

参考文档:http://docs.jiguang.cn/jpush/server/push/http_status_code/

Push v3 API 状态码 参考文档:http://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/ 

Report API 状态码 参考文档:http://docs.jiguang.cn/jpush/server/push/rest_api_v3_report/

Device API 状态码 参考文档:http://docs.jiguang.cn/jpush/server/push/rest_api_v3_device/

Push Schedule API 状态码 参考文档:http://docs.jiguang.cn/jpush/server/push/rest_api_push_schedule/ 

Release页面 有详细的版本发布记录与下载。

jpush-api-python-client's People

Contributors

cockcrow avatar curacao-1 avatar fendouai avatar hupantingxue avatar jhgdike avatar linbo avatar messense avatar panmax avatar rejown avatar ruibozhang1 avatar wind2008hxy avatar yongquanyao avatar zwczou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jpush-api-python-client's Issues

推送通知添加 'title'和 'extras'字段就报错

推送通知添加 'title'和 'extras'字段就报错

代码如下:

self.push.notification = jpush.notification(alert='test',extras={'user':'123'})

报错信息:

notification() got an unexpected keyword argument 'extras'

docs/example的下面代码有个问题

push.notification = jpush.notification(
ios=jpush.ios(
alert="JPush ios test",
badge="1",
extras={"articleid": "123456"}
),
android=jpush.android(
alert="Breaking Special Android News!",
extras={"articleid": "http://m.example.com/123456"}
)
)

badge 那里有个问题:没有双引号
badge = 1
否则会报问题:
ValueError: Invalid iOS autobadge value

example_all.py推送不成功

你们测试的时候可以正常发送吗?
我用Python版始终发送不了。经过对比java版的内容,貌似要添加push.options = 。。。行:

push = _jpush.create_push()
push.audience = jpush.all_
push.notification = jpush.notification(alert="Hello, world!")
push.platform = jpush.all_
push.options = {"send no":12345,"apns_production":False}
push.send()

这是怎么回事?

push后能否异步等待响应?

突然发现个麻烦事:貌似现在的机制是push之后只能同步收响应,这在大量并发事务下肯定要出问题。
不知有何建议?
对每个push起一个线程的话貌似代价有点大。。。

推送个多个 `alias` 时,如果某个 `alias` 找不到可能导致所有的推送都失败

假设有两个 alias,一个能找到推送的目标,一个找不到

good_alias = "good_alias"
bad_alias = "bad_alias"

然后,要将消息同时推送给两者。准备工作:

_jpush = jpush.JPush(settings.JPUSH_APP_KEY, settings.JPUSH_MASTER_SECRET)
push = _jpush.create_push()

问题来了:

push.audience = jpush.audience(jpush.alias(good_alias, bad_alias))
#...
push.send()

推送失败。两个目标都接受不到推送。

push.audience = jpush.audience(jpush.alias(bad_alias, good_alias))
#...
push.send()

改一下顺序,这样 good_alias 能收到推送。

预期

多个 audience 同时推送,每个 audience 应该互不影响。尤其对于没有保存用户和极光推送的client_id 的映射的应用。

ios无法收到推送的消息

使用python调用jpush分别发送消息给android和ios,代码如下:

[root@aps push]# cat example_platformmsg.py
import jpush as jpush
from conf import app_key, master_secret
_jpush = jpush.JPush(app_key, master_secret)

push = _jpush.create_push()
push.audience = {'registration_id': ["030fdxxxx8a","071b8xxxx15"]}
push.notification = jpush.notification(alert="Hello, JPush!(send by python)")
push.platform = jpush.all_
push.send()

[root@aps push]# python example_platformmsg.py
{"sendno":"0","msg_id":"363809640"}

android能收到,但是ios无法收到!

而使用jpush web测试推送,android和ios都可以收到消息。

[Bug] TypeError: Object of type 'bytes' is not JSON serializable

[2019-07-29 16:18:40,165: WARNING/ForkPoolWorker-4] Traceback (most recent call last):
[2019-07-29 16:18:40,165: WARNING/ForkPoolWorker-4] File "/Users/ming/Projects/lidar-backend-new/lidar/alerts/notification.py", line 64, in push_message
    push.send()
[2019-07-29 16:18:40,165: WARNING/ForkPoolWorker-4] File "/Users/ming/.local/share/virtualenvs/lidar-backend-new-P8IksPcT/lib/python3.6/site-packages/jpush/push/core.py", line 54, in send
    response = self._jpush._request('POST', body, url, 'application/json', version=3)
[2019-07-29 16:18:40,166: WARNING/ForkPoolWorker-4] File "/Users/ming/.local/share/virtualenvs/lidar-backend-new-P8IksPcT/lib/python3.6/site-packages/jpush/core.py", line 47, in _request
    raise common.JPushFailure.from_response(response)
[2019-07-29 16:18:40,166: WARNING/ForkPoolWorker-4] File "/Users/ming/.local/share/virtualenvs/lidar-backend-new-P8IksPcT/lib/python3.6/site-packages/jpush/common.py", line 73, in from_response
    response.status_code, error_code, error, json.dumps(details))
[2019-07-29 16:18:40,166: WARNING/ForkPoolWorker-4] File "/Users/ming/.pyenv/versions/3.6.5/lib/python3.6/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
[2019-07-29 16:18:40,166: WARNING/ForkPoolWorker-4] File "/Users/ming/.pyenv/versions/3.6.5/lib/python3.6/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
[2019-07-29 16:18:40,167: WARNING/ForkPoolWorker-4] File "/Users/ming/.pyenv/versions/3.6.5/lib/python3.6/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
[2019-07-29 16:18:40,167: WARNING/ForkPoolWorker-4] File "/Users/ming/.pyenv/versions/3.6.5/lib/python3.6/json/encoder.py", line 180, in default
    o.__class__.__name__)
[2019-07-29 16:18:40,167: WARNING/ForkPoolWorker-4] TypeError: Object of type 'bytes' is not JSON serializable

  • I print the response.content, and it is a bytes object
    [2019-07-29 16:18:40,099: WARNING/ForkPoolWorker-4] b'<html>\r\n<head><title>502 Bad Gateway</title></head>\r\n<body>\r\n<center><h1>502 Bad Gateway</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n'

push.send()后没有推送限制数据

在调用push.send()后仅能看到{"sendno":"0","msg_id":"*********"}
建议将header中的数据添加到response中

如jpush/push/core.py的PushResponse中
def init(self, response):
self.status_code = response.status_code
data = response.json()
for (key, value) in response.headers.items():
data[key] = value

self.payload = data

pip can't upgrade from 0.1.2 to 2.0.0

$ sudo pip install jpush==2.0.0
Downloading/unpacking jpush==2.0.0
Running setup.py egg_info for package jpush

Requested jpush==2.0.0, but installing version 0.1.2
Installing collected packages: jpush
Found existing installation: jpush 0.1.2
Can't uninstall 'jpush'. No files were found to uninstall.
Running setup.py install for jpush

Successfully installed jpush

使用这个python sdk无法推送消息

执行API 可以成功执行,但是在官网的推送历史里面看不到推送,推送没有成功。
返回的结果是
Response Payload: {u'sendno': u'0', u'msg_id': u'1067644650'}
不知道什么原因

为何不把3.2.4发布到pypi?

为何不把 3.2.4 发布到 pypi 呢,相对来说 pip install 还是比把源码放到自己的工程中要方便一点。谢谢。

jpush.common.Unauthorized

import jpush as jpush
from conf import app_key, master_secret
_jpush = jpush.JPush(app_key, master_secret)

push = _jpush.create_push()
push.audience = jpush.all_
ios_msg = jpush.ios(alert="Hello, IOS JPush!", badge="+1", sound="a.caf", extras={'k1':'v1'})
android_msg = jpush.android(alert="Hello, android msg")
push.notification = jpush.notification(alert="Hello, JPush!", android=android_msg, ios=ios_msg)
push.platform = jpush.all_
push.send()
Traceback (most recent call last):
  File "/Applications/Aptana Studio 3/plugins/org.python.pydev_3.0.0.1388187472/pysrc/pydevd.py", line 1479, in <module>
    debugger.run(setup['file'], None, None)
  File "/Applications/Aptana Studio 3/plugins/org.python.pydev_3.0.0.1388187472/pysrc/pydevd.py", line 1125, in run
    pydev_imports.execfile(file, globals, locals)  #execute the script
  File "/Users/apple/node/undo4096/tool/videoPei/test.py", line 22, in <module>
    push.send()
  File "build/bdist.macosx-10.10-x86_64/egg/jpush/push/core.py", line 46, in send
  File "build/bdist.macosx-10.10-x86_64/egg/jpush/core.py", line 45, in _request
jpush.common.Unauthorized

安装jpush时报错

Downloading/unpacking jpush (from -r requirements.txt (line 29))
  Downloading jpush-3.1.1.tar.gz
  Running setup.py (path:/opt/lambda/env/build/jpush/setup.py) egg_info for package jpush
    Traceback (most recent call last):
      File "<string>", line 17, in <module>
      File "/opt/lambda/env/build/jpush/setup.py", line 6, in <module>
        from jpush import __version__
      File "jpush/__init__.py", line 2, in <module>
        from .core import JPush
      File "jpush/core.py", line 5, in <module>
        import requests
    ImportError: No module named requests
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "/opt/lambda/env/build/jpush/setup.py", line 6, in <module>

    from jpush import __version__

  File "jpush/__init__.py", line 2, in <module>

    from .core import JPush

  File "jpush/core.py", line 5, in <module>

    import requests

ImportError: No module named requests

Hi I am having issue with master and app key

Traceback (most recent call last):
File "send.py", line 13, in
result = push.send()
File "/usr/local/lib/python3.6/site-packages/jpush/push/core.py", line 54, in send
response = self._jpush._request('POST', body, url, 'application/json', version=3)
File "/usr/local/lib/python3.6/site-packages/jpush/core.py", line 45, in _request
raise common.Unauthorized("Please check your AppKey and Master Secret")
jpush.common.Unauthorized: 'Please check your AppKey and Master Secret'

I am testing this my app_key is 2885417892eff6b9d5cc774a
and master key is E265a1347af3e653c9d1e4ce

项目说明中IOS示例android_msg未定义

Simple iOS Push中

……
>>> push.notification = jpush.notification(alert="Hello, JPush!", android=android_msg, ios=ios_msg)
……

android_msg未定义,运行会出现NameError

超时的时候无法确认是否 极光有处理

image
如果是ConnectTimeout 客户端可以重试,如果是ReadTimeout 客户端直接可以丢弃。现在�所有的超时异常返回的都是APIConnectionException, 没法判断是否需要重发。

[bug] AttributeError: 'URLError' object has no attribute 'read'

jpush/push.py ? in send_notification_by_registrationid

        self._send_msg(params)
jpush/push.py ? in _send_msg

        try:
             api_post = urllib2.urlopen(data=urllib.urlencode(params),
                                        url=API_URL, timeout=5)
             print api_post.read()
         except Exception, e:
             print e, e.read()
     #Deprecated"
     def send_notification_by_imei(self, imei, app_key, sendno, senddes,
                                   msg_title, msg_content, platform, extras={}):
         """Send notification by imei"""
'e' 
URLError(timeout('timed out',),)

jpush/push.py 第68行

pip 安装出错

pip install git+https://github.com/jpush/jpush-api-python-client
Collecting git+https://github.com/jpush/jpush-api-python-client
  Cloning https://github.com/jpush/jpush-api-python-client to /var/folders/g0/r2t_1w112x17pcq_wycw61kc0000gn/T/pip-PkRBZd-build
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/var/folders/g0/r2t_1w112x17pcq_wycw61kc0000gn/T/pip-PkRBZd-build/setup.py", line 6, in <module>
        from jpush import __version__
      File "jpush/__init__.py", line 2, in <module>
        from .core import JPush
      File "jpush/core.py", line 5, in <module>
        import requests
    ImportError: No module named requests

    ----------------------------------------
    Command "python setup.py egg_info" failed with error code 1 in /var/folders/g0/r2t_1w112x17pcq_wycw61kc0000gn/T/pip-PkRBZd-build

由于pypi中还没有更新3.0.2,我在项目的requirements.txt中只能直接从github来安装jpush。在干净的virtualenv中pip -r requirements.txt就会报如上的错误(requirements.txt中也写了requests,并且在jpush之前)。建议不要在 setup.py 中 import jpush,以避免这种问题。

在线上部署时,我不能先单独安装requests再安装requirements.txt,例如我们使用saltstack进行部署:

some-virtual-env:
  virtualenv.managed:
    - name: /path/to/some-virtual-env/
    - requirements: /path/to/requirements.txt

如果我要单独先安装 requests 库,就得现有 some-virtual-env,循环依赖了。

最关键的,还是尽快将最新版推到pypi吧,距上一次commit都已经8个多月了,还不推pypi,难道没人用么?

给reg id发送成功但是无法收到消息

日志:

DEBUG:jpush:Making POST request to https://api.jpush.cn/v3/push. Headers:
        user-agent: jpush-api-python-client
        connection: keep-alive
        content-type: application/json;charset:utf-8
Body:
        {"audience": {"registration_id": ["abcdabcd"]}, "platform": "all", "message": {"msg_content": "by_reg_id", "title": "helloworld"}}
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.jpush.cn:443
DEBUG:urllib3.connectionpool:https://api.jpush.cn:443 "POST /v3/push HTTP/1.1" 200 43
DEBUG:jpush:Received 200 response. Headers:
        Server: nginx
        Date: Wed, 11 Dec 2019 14:04:53 GMT
        Content-Type: application/json
        Content-Length: 43
        Connection: keep-alive
        X-Rate-Limit-Limit: 600
        X-Rate-Limit-Remaining: 599
        X-Rate-Limit-Reset: 60
        X-Jpush-Timestamp: 1576073093486
Body:
        b'{"sendno":"0","msg_id":"47287830529285706"}'

但是用web界面根据reg id发送却能收到。

代码:

def __push_notify_by_reg_id(message, reg_id):
    try:
        push = jp.create_push()
        push.audience = jpush.audience(jpush.registration_id(reg_id))
        push.message = jpush.message(message.brief, message.title)
        push.platform = jpush.all_

        push.send()
    except Exception:
        logging.exception("failed to push message(%d)", message.id)

求发新版呀

都快一年没发 PyPI 新版了,支持 Python 3 的 PR merge 了也半年了,广大 Python 3 用户求 pip 安装呀。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.