AIRFLOW 企业微信发送

编写wechat_hook.py

import json
from typing import List, Optional, Union
import requests
from requests import Session
from airflow.exceptions import AirflowException
from airflow.providers.http.hooks.http import HttpHook


class WechatHook(HttpHook):

    conn_name_attr = 'wechat_conn_id'
    default_conn_name = 'wechat_default'
    conn_type = 'http'
    hook_name = 'Wechat'

    def __init__(
        self,
        wechat_conn_id='wechat_default',
        message_type: str = 'text',
        message: Optional[Union[str, dict]] = None,
        at_mobiles: Optional[List[str]] = None,
        at_all: bool = False,
        *args,
        **kwargs,
    ) -> None:
        super().__init__(http_conn_id=wechat_conn_id, *args, **kwargs)  # type: ignore[misc]
        self.message_type = message_type
        self.message = message
        self.at_mobiles = at_mobiles
        self.at_all = at_all

    def _get_endpoint(self) -> str:
        """Get WeChat endpoint for sending message."""
        conn = self.get_connection(self.http_conn_id)
        token = conn.password
        if not token:
            raise AirflowException(
                'WeChat token is requests but get nothing, check you conn_id configuration.'
            )
        return f'cgi-bin/webhook/send?key={token}'

    def _build_message(self) -> str:
        """
        Build different type of WeChat message
        As most commonly used type, text message just need post message content
        rather than a dict like ``{'content': 'message'}``
        """
        if self.message_type in ['text', 'markdown']:
            data = {
                'msgtype': self.message_type,
                self.message_type: {'content': self.message} if self.message_type == 'text' else self.message,
                'at': {'atMobiles': self.at_mobiles, 'isAtAll': self.at_all},
            }
        else:
            data = {'msgtype': self.message_type, self.message_type: self.message}
        return json.dumps(data)

    def get_conn(self, headers: Optional[dict] = None) -> Session:
        """
        Overwrite HttpHook get_conn because just need base_url and headers and
        not don't need generic params
        :param headers: additional headers to be passed through as a dictionary
        """
        conn = self.get_connection(self.http_conn_id)
        self.base_url = conn.host if conn.host else 'https://qyapi.weixin.qq.com'
        session = requests.Session()
        if headers:
            session.headers.update(headers)
        return session

    def send(self) -> None:
        """Send WeChat message"""
        support_type = ['text', 'link', 'markdown', 'actionCard', 'feedCard']
        if self.message_type not in support_type:
            raise ValueError(
                f'WeChatWebhookHook only support {support_type} so far, but receive {self.message_type}'
            )

        data = self._build_message()
        self.log.info('Sending WeChat type %s message %s', self.message_type, data)
        resp = self.run(
            endpoint=self._get_endpoint(), data=data, headers={'Content-Type': 'application/json'}
        )

        # WeChat success send message will with errcode equal to 0
        if int(resp.json().get('errcode')) != 0:
            raise AirflowException(f'Send WeChat message failed, receive error message {resp.text}')
        self.log.info('Success Send WeChat message')

编写wechat_operator.py

from typing import TYPE_CHECKING, List, Optional, Sequence, Union
from airflow.models import BaseOperator
from wechat_hook import WechatHook
if TYPE_CHECKING:
    from airflow.utils.context import Context

class WechatOperator(BaseOperator):

    template_fields: Sequence[str] = ('message',)

    ui_color = '#4ea4d4'  # Wechat icon color

    def __init__(
        self,
        *,
        wechat_conn_id: str = 'wechat_default',
        message_type: str = 'text',
        message: Union[str, dict, None] = None,
        at_mobiles: Optional[List[str]] = None,
        at_all: bool = False,
        **kwargs,
    ) -> None:
        super().__init__(**kwargs)
        self.wechat_conn_id = wechat_conn_id
        self.message_type = message_type
        self.message = message
        self.at_mobiles = at_mobiles
        self.at_all = at_all

    def execute(self, context: 'Context') -> None:
        self.log.info('Sending WeChat message.')
        hook = WechatHook(
            self.wechat_conn_id,
        self.message_type, 
        self.message, 
        self.at_mobiles, 
        self.at_all
        )
        hook.send()

测试文件

from wechat_operator import WechatOperator
context='22222'
message = '1111111'
WechatOperator(
    task_id='wechat_task',
    wechat_conn_id='wechat_default',
    message_type='text',
    message=message,
    at_all=True,
).execute(context)

在这里插入图片描述

参考1:https://blog.csdn.net/weixin_40791632/article/details/125317428
参考2:https://blog.csdn.net/qq_31405633/article/details/100521402

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Airflow汉化指的是将开源工作流编排工具Airflow的界面和相关文档进行翻译为中文。Airflow是一个由Apache基金会孵化的项目,它提供了一种可视化的方式来编排、调度和监控数据处理任务。 汉化Airflow有以下几个主要的原因和优势: 1. 提升用户体验:将Airflow界面和相关文档翻译为中文,可以提升中国用户的使用体验和学习效果。对于不熟悉英文的用户来说,使用母语进行操作可以让他们更容易理解和掌握工具的功能和特性。 2. 方便本地化部署:随着中国数据处理领域的迅速发展,越来越多的企业和组织开始采用Airflow进行工作流的管理。汉化Airflow使得本地化部署更加方便,能够更好地满足国内用户的需求。 3. 促进社区发展:开源软件的发展需要全球开发者的参与,而Airflow的汉化可以吸引更多中文用户参与到社区中来。他们可以贡献代码、提交BUG、提供反馈等,为Airflow的改进和完善做出贡献。 4. 推广和普及:随着Airflow在中国的使用越来越广泛,汉化可以更好地推广和普及这个工作流编排工具。通过本土化的努力,能够让更多用户了解和尝试使用Airflow,进而提升其影响力和社区规模。 总之,Airflow的汉化对于提升用户体验、方便本地化部署、促进社区发展和推广普及都有着重要的作用。希望越来越多的人参与到Airflow的汉化工作中来,共同推动这个开源工作流编排工具的发展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值