异步协程 aiohttp 实现企业微信消息推送报警

  • 异步协程 

    aiohttp  注意语法糖 (async \await )异步调运 

    关键词

    event_loop 事件循环:程序开启一个无限的循环,程序员会把一些函数注册到事件循环上。当满足事件发生的时候,调用相应的协程函数。

    coroutine 协程:协程对象,指一个使用async关键字定义的函数,它的调用不会立即执行函数,而是会返回一个协程对象。协程对象需要注册到事件循环,由事件循环调用。

    task  任务:一个协程对象就是一个原生可以挂起的函数,任务则是对协程进一步封装,其中包含任务的各种状态。

    future: 代表将来执行或没有执行的任务的结果。它和task上没有本质的区别

    async/await 关键字:python3.5 用于定义协程的关键字,async定义一个协程,await用于挂起阻塞的异步调用接口。

     

    # !/usr/bin/python3
    # -*- coding: utf-8 -*-
    # Author: WangChao
    
    
    import asyncio
    import json
    import logging
    import time
    from aiohttp import ClientSession
    
    
    class Aiowechat:
        options = None
    
        def __init__(self, options=None):
            self.options = options if isinstance(options, dict) else dict()
            self.token_now = 0
            self.token = None
    
        @staticmethod
        async def load_logger():
            logger = logging.getLogger(name=__name__)
            return logger
    
        @staticmethod
        def load_env():
            options = {
                'corpid': '************',
                'corpsecret': '************',
                'url': 'https://qyapi.weixin.qq.com',
            }
            return options
    
        async def get_token(self):
            """获取token值"""
            if int(time.time()) - self.token_now > 7000:
                token_url = '%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s' % (self.url, self.corpid, self.corpsecret)
                async with ClientSession() as session:
                    async with session.get(token_url) as response:
                        content = await response.read()
                        token = json.loads(content.decode()).get('access_token', '')
                        self.token = token
                        self.token_now = int(time.time())
            return self.token
    
        @staticmethod
        async def messages(touser, wechat_msg):
            """构建发送数据"""
            values = {
                "touser": touser,
                "msgtype": "text",
                "agentid": 1000007,
                "text": {
                "content": wechat_msg, },
                "safe": 0,
                "enable_id_trans": 0,
                "enable_duplicate_check": 0,
            }
            msges = (bytes(json.dumps(values), 'utf-8'))
            return msges
    
        async def send(self, touser, wechat_data):
            """发送"""
            token = await self.get_token()
            msg = wechat_data.get('msg')
            send_url = '%s/cgi-bin/message/send?access_token=%s' % (self.url, token)
            data = await self.messages(touser, msg)
            async with ClientSession() as session:
                async with session.post(send_url, data=data) as response:
                    response = await response.read()
                    state = json.loads(response.decode()).get('errcode', '')
    
            logger = await self.load_logger()
            if state == 0:
                logger.warning('企业微信报警通知 to-{} 成功'.format(touser))
    
            else:
                logger.error('企业微信报警通知 to-{0}失败 状态码:{1}'.format(touser, state))
    
        async def exec(self, data):
            tousers = data.get('tousers')
            tasks = []
            for touser in tousers:
                tasks.append(asyncio.ensure_future(self.send(touser, data)))
            return tasks
    
    
    if __name__ == '__main__':
        we = Aiowechat(Aiowechat.load_env())
        data = {
            'tousers': ['************'],
            'msg': '多人测试',
        }
        loop = asyncio.get_event_loop()
        tasks = loop.run_until_complete(we.exec(data=data))
        loop.run_until_complete(asyncio.wait(tasks))

     


    欢迎大佬指正
    ** 原创 转载需注明 **

posted @ 2020-03-06 15:23  iotwolves  阅读(111)  评论(0编辑  收藏  举报