Python(35):Python3 通过https上传文件和下载文件

Python(35):Python3 通过https上传文件和下载文件

Python http方式的下载,参考:https://blog.csdn.net/fen_fen/article/details/113753983

https需要先安装需要的模块

1、上传示例

1.1、调用:

复制代码
upload_strategy(access_token,"123456789")

1.2、上传代码

python 复制代码
global pkcs12_filename, pkcs12_password
pkcs12_filename = './conf/xxx-client-cert-xxx.p12'
pkcs12_password = 'xxx'
self.host=10.1.1.101



# 上传文件
    def upload_file(self, access_token,appid):
        #warnings.simplefilter('ignore', ResourceWarning)
        # filepath = os.getcwd()
        # print(filepath)
        # print(filepath+"\data\\"+fileName)
        try:
            header_up = {"Authorization": "Bearer " + access_token}
            file=open("./data/"+fileName, "rb")
            files={"file": file}
            #files = {"file": open("./data/"+fileName, "rb")}
            url = "https://"+self.host+"/xxx/v1/xxx/strategy/xxx?appId="+appid

            api_json = base_request.upload_request(url, header_up, files)
            if api_json["code"] == 0:
                print(">>上传策略成功。")
            else:
                print(">>上传策略失败,", api_json)
            file.close()
            return api_json
        except Exception as e:
            print(">>上传策略失败,Exception:", e)
python 复制代码
# 基础请求:上传
def upload_request(url, headers, files):
    response = requests_pkcs12.post(url, headers=headers, files=files,
                                    pkcs12_filename=pkcs12_filename,
                                    pkcs12_password=pkcs12_password, verify=False)
    api_json = response.json()  # 获取请求返回实际结果的json串值
    return api_json

2、下载示例

2.1、下载调用:

python 复制代码
   self.host=10.1.1.101
 
    # 下载客户端
    def download_client(self, header_all):
        try:
            url = "https://" + self.host + "/xxx/v1/xxx/download-client"
            getfile = Getfile(url, header_all)
            filename = getfile.getfilename()
            #print(filename)
            if filename:
                getfile.download(filename)

        except Exception as e:
            print(">>下载客户端失败,Exception: ", e)


header_all = {"Content-Type": "application/json;charset=UTF-8"}
header_all['Authorization'] = "Bearer " + access_token
download_client(header_all)

2.2、Python3 https下载文件工具类:

python 复制代码
# -*- coding: utf-8 -*-

"""
Create by HMF on 2024/01/11.
"""
import re,time
import requests
import requests_pkcs12

class Getfile(object):  # 下载文件
    global pkcs12_filename, pkcs12_password
    pkcs12_filename = './conf/xxx-client-cert-xxx.p12'
    pkcs12_password = 'xxx'

    def __init__(self, url, headers):
        self.url = url
        self.headers = headers

    def getheaders(self):
        try:
            #r = requests_pkcs12.head(self.url, headers=self.headers, verify=False)
            r = requests_pkcs12.head(self.url, headers=self.headers, pkcs12_filename=pkcs12_filename, pkcs12_password=pkcs12_password, verify=False)
            rs_headers = r.headers
            return rs_headers
        except Exception as e:
            print(e)

    # 获取默认下载文件名
    def getfilename(self):
        try:
            if 'Content-Disposition' in self.getheaders():
                file = self.getheaders().get('Content-Disposition')
                # filename = re.findall('filename="(.*)"',file)
                filename = re.split("=", file)[1]
                if filename:
                    print("下载文件名:" + filename)
                    return filename
            else:
                print("下载文件失败")
        except Exception as e:
            print(e)

    # 下载文件
    def download(self, filename): 
        try:
            #self.r = requests_pkcs12.get(self.url, headers=self.headers, stream=True, verify=False)
            self.r =requests_pkcs12.get(self.url, headers=self.headers,pkcs12_filename=pkcs12_filename,
                                 pkcs12_password=pkcs12_password, stream=True,  verify=False)

            with open(filename, "wb") as code:
                # 边下载边存硬盘
                for chunk in self.r.iter_content(chunk_size=1024): 
                    if chunk:
                        code.write(chunk)
            time.sleep(1)
        except Exception as e:
            print(e)
相关推荐
轻口味27 分钟前
命名空间与模块化概述
开发语言·前端·javascript
晓纪同学1 小时前
QT-简单视觉框架代码
开发语言·qt
威桑1 小时前
Qt SizePolicy详解:minimum 与 minimumExpanding 的区别
开发语言·qt·扩张策略
飞飞-躺着更舒服1 小时前
【QT】实现电子飞行显示器(简易版)
开发语言·qt
明月看潮生2 小时前
青少年编程与数学 02-004 Go语言Web编程 16课题、并发编程
开发语言·青少年编程·并发编程·编程与数学·goweb
明月看潮生2 小时前
青少年编程与数学 02-004 Go语言Web编程 17课题、静态文件
开发语言·青少年编程·编程与数学·goweb
Java Fans2 小时前
C# 中串口读取问题及解决方案
开发语言·c#
盛派网络小助手2 小时前
微信 SDK 更新 Sample,NCF 文档和模板更新,更多更新日志,欢迎解锁
开发语言·人工智能·后端·架构·c#
算法小白(真小白)2 小时前
低代码软件搭建自学第二天——构建拖拽功能
python·低代码·pyqt
唐小旭2 小时前
服务器建立-错误:pyenv环境建立后python版本不对
运维·服务器·python