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)
相关推荐
哈里谢顿2 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户83562907805116 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng818 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi19 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee19 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay19 小时前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤20 小时前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean20 小时前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽21 小时前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
用户60648767188961 天前
国内开发者如何接入 Claude API?中转站方案实战指南(Python/Node.js 完整示例)
人工智能·python·api