python文件上传的三种方式

一、from_data类型上传

这是封装的request请求

import requests
import urllib3

urllib3.disable_warnings()

class HttpClient:

    def __init__(self):
        self.client = requests.session()

    def send_request(self, data):
        """发送请求"""
        response = self.client.request(verify=False, **data)
        return response

    def close_session(self):
        """关闭会话"""
        self.client.close()

这是封装的文件上传接口,需要注意的是参数header的content-type要data.content_type,才能以表单方式上传文件

from requests_toolbelt import MultipartEncoder

from common.http_client import HttpClient
from utils.utils import read_api_yaml


class UploadFile(HttpClient):
    """
    文件导入接口
    """

    def __init__(self, url, token):
        super(UploadFile, self).__init__()
        self.upload_file_url = read_api_yaml("upload_file_url")
        self.url = url
        self.token = token

    def upload_file(self, local_file_path, file_name):
        """
        调用文件交互子系统上传文件
        local_file_path:本地文件路径
        file_name:文件名
        """

        data = MultipartEncoder(fields={"Content-Disposition": (file_name, open(local_file_path, "rb"), "text/plain")})
        params = {
            "url": self.url + self.upload_file_url,
            "headers": {"token": self.token, 'Content-Type': data.content_type, },
            "method": "POST",
            "data": data
        }

        return self.send_request(data=params)

另外,"text/plain"需要与上传文件接口的类型一致,可以询问开发或者查看接口文档,或者抓包获取接口信息等等方式来确定。

二、raw类型上传

import requests

file = open('E:/test.xml','rb')
requests.post(url=url,data=file.read(),headers={'Content-Type':'text/xml'})

三、binary类型上传

import requests

files={'file':open('E:/test.xml','rb')}
requests.post(url=url, files=files, headers={'Content-Type':'binary'})
posted @ 2023-03-08 17:02  xyztank  阅读(4903)  评论(0编辑  收藏  举报