Python:极光推送(Jpush)

极光推送的整体流程:

APP -->注册过滤字段(device_id、robot.uuid)--> 后台指定过滤字段 -->极光服务器发送给指定APP

与Python交互

1、celery异步任务

@app.task
def jpush_message(method, **kwargs):
    log.info('jpush mesaage start')
    # 通过jpush_api调用jpush   API
    if hasattr(jpush_api, method):
        method_func = getattr(jpush_api, method)
        response = method_func(**kwargs)
        log.info('jpush mesaage response: %s' % response)
        if response:
            return 'change state success'
        return 'change state error'
    return 'jpush error ,no have%s' % method

2、jpush  API

_jpush = jpush.JPush(JPUSH_APP_KEY, JPUSH_MASTER_SECRET)
_jpush.set_logging("DEBUG")

import base64


def alias(message, title=None, list_alias=None, list_tags=None):
    log.info("title :%s,  list_alias: %s list_tags:%s" % (str(title), str(list_alias), str(list_tags)))
    messages = base64.b64encode(str(message).encode('utf-8'))
    msg = messages.decode('utf-8')
    push = _jpush.create_push()

    if list_alias:
        alias1 = {"alias": list_alias}
    if list_tags:
        if len(list_tags) > 1:
            tags = {"tag_and": list_tags}
        else:
            tags = {"tag": list_tags}

    if list_alias is None and list_tags is None:
        push.audience = jpush.audience('all')
    elif not list_alias:
        push.audience = tags
    elif not list_tags:
        push.audience = alias1
    else:
        push.audience = tags.update(alias1)

    if title:
        push.notification = jpush.notification(alert=title)

    push.message = jpush.message(msg)
    push.platform = jpush.all_
    push.options = {"apns_production": False}
    log.info(str(push.payload))
    try:
        push.send()
    except Exception as e:
        log.info('message: %s, except: %s' % (str(message), str(e)))
        return False
    else:
        log.info('message: %s, success' % str(message))
        return True

3、使用

# 极光推送
content = {"task_res": -1, 'task_type': main_task, 'clean_mode': -1, 'error_code': error_code,"robot_name": robot_obj.robot_name}
data = MessageResponse(title='robot error', code=settings.JPUSH_MESSAGE_TYPE_DICT['robot_error'],content=content)
message = data.jsonify()
# 中文推送
cn_title = get_error_title(robot_obj.robot_name, error_code, "cn")
# "alias":推送的方法,message:推送的内容,list_tags:指定过滤字段,title:推送给主页面的主题
jpush_message('alias', message=message, list_tags=[robot_obj.uuid, settings.tag["cn"]],title=cn_title, )
# 英文推送
en_title = get_error_title(robot_obj.robot_name, error_code, "en")
jpush_message('alias', message=message, list_tags=[robot_obj.uuid, settings.tag["en"]],title=en_title, )

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值