https资源下载到本地+钉钉上传资源+发送钉钉工作通知完整链路实现

0、解决urllib.error.URLError: 报错

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

一、https资源下载到本地

    from urllib.request import urlretrieve
import os
 
 
def download(url, savepath='./'):
    """
    download file from internet
    :param url: path to download from
    :param savepath: path to save files
    :return: None
    """
    def reporthook(a, b, c):
        """
        显示下载进度
        :param a: 已经下载的数据块
        :param b: 数据块的大小
        :param c: 远程文件大小
        :return: None
        """
        print("\rdownloading: %5.1f%%" % (a * b * 100.0 / c), end="")
    filename = os.path.basename(url)
    # 判断文件是否存在,如果不存在则下载
    if not os.path.isfile(os.path.join(savepath, filename)):
        print('Downloading data from %s' % url)
        urlretrieve(url, os.path.join(savepath, filename), reporthook=reporthook)
        print('\nDownload finished!')
    else:
        print('File already exsits!')
    # 获取文件大小
    filesize = os.path.getsize(os.path.join(savepath, filename))
    # 文件大小默认以Bytes计, 转换为Mb
    print('File size = %.2f Mb' % (filesize/1024/1024))
 
if __name__ == '__main__':
    # 以下载cifar-10数据集为例
    url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
    download(url, savepath='./')

二、钉钉上传资源

    def ddupload(self, route):
        url = f'{dd_domain}/media/upload?access_token={self.access_token}'
        data = {
            "type": 'image',
            "media": str(route),
        }
        files = {
            'media': open(route, 'rb')
        }
        res_json = requests.post(url=url, data=data, files=files).json()
        return res_json

三、python url转二维码

pip install image qrcode pillow 
# 基础
import qrcode
img=qrcode.make("www.zhuanzhuan.com")
img.save("./test.png")

# 更改样式,宽度、大小、容错系数

import qrcode
qr = qrcode.QRCode(
	version=2,
	error_correction=qrcode.constants.ERROR_CORRECT_L,
	box_size=10,
	border=1
)#设置二维码的大小
qr.add_data("https://blog.csdn.net/caidewei121/")
qr.make(fit=True)
img = qr.make_image()
img.save("my_blog.png")


# 将本地图片粘贴上去

import qrcode
from PIL import Image
 
url="www.zhuanzhuan.com"
qr=qrcode.QRCode(
    version=2,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=8,
    border=2
    )
qr.add_data(url)
qr.make(fit=True)
img=qr.make_image()
img=img.convert("RGBA")
icon=Image.open("ABLOGO.png").convert("RGBA")  
img_w,img_h=img.size
factor=4
size_w=int(img_w/factor)
size_h=int(img_h/factor)
 
icon_w,icon_h=icon.size
if icon_w>size_w:
    icon_w=size_w
if icon_h>size_h:
    icon_h=size_h
icon=icon.resize((icon_w,icon_h),Image.ANTIALIAS)
 
w=int((img_w-icon_w)/2)
h=int((img_h-icon_h)/2)
img.paste(icon,(w,h),icon)
 
img.save("./test.png")


你可能感兴趣的:(钉钉,python,开发语言)