Python 2.7使用飞书上传图片的功能

近期公司全部换成了飞书作为通讯的工具,之前的企业微信的机器人和写法都得重新写过了。

所以在打包以后的构建通知等都要通过飞书来通知。当然普通的通知写法很简单,带有图片的会有点麻烦。

但是比较蛋疼的是,公司打包的机器上只有Python2.7(WHATTHEFXXK)。

没有办法,虽然Python2.7很蛋疼,但是也只能上了。

在飞书的官方上有提供Python3.X版本的写法,我这里也就不多说了。

主要讲讲,Python2.7的一个写法。

其实一开始走了不少的各种弯路,总是以为是图片的编码问题?因为Python总是报的编码的错误。

于是总是在图片相关的编码上的问题上纠结。

 

后面我才发现了一个巨大的坑!这个坑是之前没有想到的。

问题出在headers上,由于编码上的不同,Python2.7传入的参数内是带有u'...'

比如,我编写了一个字符串number,输出到网页上,变成了u'number'

原因:python2.7支持unicode编码和utf-8编码两种,显示时显示成u‘number’表明这是一个unicode编码的字符串,所以转换成utf-8就不显示成u'number'啦!~

虽然有些人说其实他不会影响程序的运行,但是由于我是传入的参数,传错了就会导致有各种的报错,于是我就炸了,搞了半天。

然后我会附上2.7如何运行的代码!注意是2.7!2.7!2.7!

 

    def upload_image(self, image_path):
        postUrl = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
        payload_message = {
            "app_id": "", #填写你的机器人的app_id
            "app_secret": "" #填写你的机器人的app_secret
        }
        headers = {
            'Content-Type': 'application/json'
        }
        response = requests.request("POST", postUrl, headers=headers, data=json.dumps(payload_message))
        content = response.json()
        if content.get("code") != 0:
            raise Exception("Call Api Error, errorCode is %s" % content["code"])

        token = content.get("tenant_access_token")
        with open(image_path, 'rb') as f:
            image = f.read()
            
        resp = requests.post(
            url='https://open.feishu.cn/open-apis/image/v4/put/',
            headers={'Authorization': "Bearer " + token.encode('utf-8')},
            files={
                "image": image
            },
            data={
                "image_type": "message"
            },
            stream=True)
        resp.raise_for_status()
        content = resp.json()
        print(content)
        if content.get("code") == 0:
            return content
        else:
            raise Exception("Call Api Error, errorCode is %s" % content["code"])

啊,写2.7心好累,还是3.X爽

posted @ 2021-06-25 09:46  黑羽青衣  阅读(826)  评论(0编辑  收藏  举报