您的位置:首页 > 编程语言 > Python开发

Jpush推送之服务器端Python SDK

2018-01-05 13:57 549 查看
一、

手机端的apk的安装:

首先到极光推送官网上https://www.jiguang.cn/dev/#/app/51f30fc43b4c8d8b3dcad634/pushEdit,填好信息,然后会生成一个Android demo。下载下来即可。



然后用Android studio打开该项目,并且依据安装Android studio时D:\software\Android_install\android studio\gradle\m2repository\com\android\tools\build\gradle目录下的最新版本



进行修改:



最后,可以运行该项目,安装apk到手机上。

二、

后台jpush的实现:

首先,在cmd命令终端,输入pip freeze查看,查看已经安装的python软件包和版本。发现jpush 版本是3.2.8

然后参考官网:https://pypi.python.org/pypi/jpush/3.2.8


jpush 3.2.8

JPush's officially supported Python client library

=======================
JPush API Python Client
=======================

JPush's officially supported Python client library for accessing JPush APIs. 

JPush Rest API Documents: http://docs.jpush.io/server/rest_api_v3_push/
You can download the latest release file here:http://github.com/jpush/jpush-api-python-client/releases

1、

------------
Installation
------------
To install jpush-api-python-client, simply:

$ sudo pip install jpush

or alternatively install via easy_install:

$ sudo easy_install jpush

or from source:

$ sudo python setup.py install

2、

-------
Testing
-------
For running the tests, you need the standard `unittest` module, shipped
with Python. 

To run jpush-api-python-client tests, simply:

$ nosetests  tests/push   tests/devices --verbosity=2 

3、

--------
Examples
--------
You can see more examples in https://github.com/jpush/jpush-api-python-client/blob/master/examples

找到下载的http://github.com/jpush/jpush-api-python-client/releases

进入项目目录:



---------------------

SimpleiOSPush
---------------------
>>> import jpush as jpush
>>> from tests.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.options = {"time_to_live":86400, "sendno":12345,"apns_production":True}
>>> push.platform = jpush.platform("ios")
>>> push.send()

-----------------

Get taglist
-----------------
>>> import jpush as jpush
>>> from conf import app_key, master_secret
>>> _jpush = jpush.JPush(app_key, master_secret)
>>> device = _jpush.create_device()
>>> device.get_taglist()

--------
Questions
--------
The best place to ask questions is our community site: http://community.jpush.cn/
----------------------
Simple Android Push-----message(自定义消息)

--------------------------



效果为:



三、

整理二:后台推送脚本代码

#-*- coding:utf-8 -*-
import jpush as jpush
# from tests.conf import app_key,master_secret
app_key = u'51f30fc2222222222222dca22234'
master_secret = u'2282222222204b522222a0b2'
_jpush=jpush.JPush(app_key,master_secret)##1、初始化JPush,获取AppKey,Master Secret;实例化JPush,
push=_jpush.create_push()
#--------------------------------推送设备对象---------------------------
#一个推送对象,以 JSON 格式表达,表示一条推送相关的所有信息。
#push.audience=jpush.all_ ;#audience	必填	推送设备指定;确认推送设备对象,JPush 提供了多种方式,比如:别名、标签、注册ID、分群、广播等。
push.audience = jpush.audience(
jpush.registration_id("18071adc0308b6e0dc2",),
)
#-----------------------------------------------------------------------

#----------------------------自定义消息 发给android的实现---------------
push.message=jpush.message("{'salists': [{'payType': 1, 'proid': 3, 'name': '燕麦谷粒多', 'count': 1, 'sinPrice': 2, 'toPrice': 2, 'chid': 162}], 'nums': 1}");#message	可选	消息内容体。是被推送到客户端的内容。与 notification 一起二者必须有其一,可以二者并存
#------------------------------------------------------------------------

#--------------------------- 发送通知 给android的实现--------------------
# android = jpush.android(alert={
# "salists": [
# {
# "payType": 1,
# "proid": 3,
# "name": "燕麦谷粒多",
# "count": 1
# }
# ],
# "nums": 1
# }, priority=1, style=2,inbox=2, alert_type=1, extras={'k1':'v1'})#通知栏样式类型:inbox=2,big_text=1,bigPicture=3
# push.notification = jpush.notification(alert="Hello, JPush!", android=android,)#注意notification的alert没起作用,被android中的alert覆盖掉了。
#------------------------------------------------------------------------

push.platform=jpush.all_#platform	必填	推送平台设置
push.send()

运行:



运行试验结果:



四、jpush---之devices

1、首先在手机jpush app 上设置tag:



import jpush as jpush
#from conf import app_key, master_secret
app_key = u'dfdgdfsdfsfsfsfb3dcad634'
master_secret = u'fsdfsfdsfsfsdfd630a0b2'

_jpush = jpush.JPush(app_key, master_secret)
device = _jpush.create_device()
print(device.get_taglist())

运行结果为:



2、知识点:

标签 tag

为安装了应用程序的用户,打上标签。其目的主要是方便开发者根据标签,来批量下发 Push 消息。

可为每个用户打多个标签。

举例: game, old_page, women

3、全部有关device部分的程序:

'Device API 用于在服务器端查询、设置、更新、删除设备的 tag,alias 信息。'
import jpush as jpush
app_key = u'533c232323ad424232334'
master_secret = u'8323231223232320b2'
_jpush = jpush.JPush(app_key, master_secret)
device = _jpush.create_device()

import urllib3
import socket
#In Python 2.7.3
#try:
# urllib2.urlopen("www.baidu.com", timeout = 10)

#from conf import app_key, master_secret
alias = "魅族X5"
tag='huan'#在手机APP端已经设置好的
platform='android,ios'
reg_id='134354354565656565652'
#=====================在程序端给设备增加tags标志============
entity = jpush.device_tag(jpush.add("lele", "xiaoxiao"))#此时,该设备应该含有三个tags
#entity = jpush.device_tag("")#就是将设备的所有tags清空了。
result=device.set_devicemobile(reg_id, entity)
#============================================================

#======================给设备添加mobile======================
mobile=jpush.device_mobile('132332313420')
result=device.set_devicemobile(reg_id,mobile)
#============================================================
print(result.status_code)#200

print(result.payload)#success

print(device.get_aliasuser(alias,platform))#Device response Payload: {'registration_ids': ['18432222343434234dc2']}

print(device.get_taglist())#{'tags':['huanhuan','lele','xiaoxiao']}

print(device.check_taguserexist(tag, reg_id))#Device response Payload: {'result': True}

print(device.get_deviceinfo(reg_id))#{'mobile':None,'alias':'','tags':['huanhuan','lele','xiaoxiao']}

# print(device.delete_tag("xiaoxiao", platform))#删除该该平台上凡是xiaoxiao的tags

# except urllib3.URLError as e: #AttributeError: module 'urllib3' has no attribute 'URLError'
# print (type(e))    #not catch
# except socket.timeout as e:
# print (type(e))    #catched

运行结果为:



存在的问题为:

有时候,一直运行该脚本时,会出现如下错误 :

D:\Jpush\jpush-api-python-client-3.2.8\jpush-api-python-client-3.2.8>python get_
taglist.py
Traceback (most recent call last):
File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 38
7, in _make_request
six.raise_from(e, None)
File "<string>", line 2, in raise_from
File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 38
3, in _make_request
httplib_response = conn.getresponse()
File "D:\software\python\lib\http\client.py", line 1331, in getresponse
response.begin()
File "D:\software\python\lib\http\client.py", line 297, in begin
version, status, reason = self._read_status()
File "D:\software\python\lib\http\client.py", line 258, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "D:\software\python\lib\socket.py", line 586, in readinto
return self._sock.recv_into(b)
File "D:\software\python\lib\ssl.py", line 1002, in recv_into
return self.read(nbytes, buffer)
File "D:\software\python\lib\ssl.py", line 865, in read
return self._sslobj.read(len, buffer)
File "D:\software\python\lib\ssl.py", line 625, in read
v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\software\python\lib\site-packages\requests\adapters.py", line 440, in
send
timeout=timeout
File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 63
9, in urlopen
_stacktrace=sys.exc_info()[2])
File "D:\software\python\lib\site-packages\urllib3\util\retry.py", line 357, i
n increment
raise six.reraise(type(error), error, _stacktrace)
File "D:\software\python\lib\site-packages\urllib3\packages\six.py", line 686,
in reraise
raise value
File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 60
1, in urlopen
chunked=chunked)
File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 38
9, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File "D:\software\python\lib\site-packages\urllib3\connectionpool.py", line 30
9, in _raise_timeout
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % time
out_value)
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='device.jpush.cn',
port=443): Read timed out. (read timeout=30)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\Jpush\jpush-api-python-client-3.2.8\jpush-api-python-client-3.2.8\jpu
sh\core.py", line 32, in _request
response = self.session.request(method, url, data=body, params=params, heade
rs=headers, timeout=30)
File "D:\software\python\lib\site-packages\requests\sessions.py", line 502, in
request
resp = self.send(prep, **send_kwargs)
File "D:\software\python\lib\site-packages\requests\sessions.py", line 612, in
send
r = adapter.send(request, **kwargs)
File "D:\software\python\lib\site-packages\requests\adapters.py", line 516, in
send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='device.jpush.cn', por
t=443): Read timed out. (read timeout=30)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "get_taglist.py", line 15, in <module>
result=device.set_devicemobile(reg_id, entity)
File "D:\Jpush\jpush-api-python-client-3.2.8\jpush-api-python-client-3.2.8\jpu
sh\device\core.py", line 50, in set_devicemobile
info = self.send("POST", url, body)
File "D:\Jpush\jpush-api-python-client-3.2.8\jpush-api-python-client-3.2.8\jpu
sh\device\core.py", line 18, in send
response = self._jpush._request(method, body, url, content_type, version=3)
File "D:\Jpush\jpush-api-python-client-3.2.8\jpush-api-python-client-3.2.8\jpu
sh\core.py", line 36, in _request
raise common.APIConnectionException("Connection to api.jpush.cn error.")
jpush.common.APIConnectionException: 'Connection to api.jpush.cn error.'

D:\Jpush\jpush-api-python-client-3.2.8\jpush-api-python-client-3.2.8>

发现了下面的回答:(不知道是不是我上面问题的答案,总之开通了443端口了)
!!求助—内网服务器访问极光服务器–连接错误(https://community.jiguang.cn/t/topic/9559/3



五、
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python jpush