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)
相关推荐
Rverdoser7 分钟前
RabbitMQ的基本概念和入门
开发语言·后端·ruby
dj244294570710 分钟前
JAVA中的Lamda表达式
java·开发语言
谢眠16 分钟前
深度学习day3-自动微分
python·深度学习·机器学习
z千鑫25 分钟前
【人工智能】深入理解PyTorch:从0开始完整教程!全文注解
人工智能·pytorch·python·gpt·深度学习·ai编程
流星白龙41 分钟前
【C++习题】10.反转字符串中的单词 lll
开发语言·c++
尘浮生1 小时前
Java项目实战II基于微信小程序的校运会管理系统(开发文档+数据库+源码)
java·开发语言·数据库·微信小程序·小程序·maven·intellij-idea
MessiGo1 小时前
Python 爬虫 (1)基础 | 基础操作
开发语言·python
Tech Synapse1 小时前
Java根据前端返回的字段名进行查询数据的方法
java·开发语言·后端
乌啼霜满天2491 小时前
JDBC编程---Java
java·开发语言·sql
肥猪猪爸1 小时前
使用卡尔曼滤波器估计pybullet中的机器人位置
数据结构·人工智能·python·算法·机器人·卡尔曼滤波·pybullet