requests
说明
post文件到服务器时, header需要增加一个特殊的头信息:Content-Type
使用模块
datDict = {‘taskIds1’: ‘178626139458322436’, ‘filename1’: ‘tempIntergface.xlsx’, ‘files1’: ‘./tempIntergface.xlsx’)}
# 引入模块
import requests,sys,os
# 传文件时, 指定 method参数为 post-file
def agencyRequest(method, targetURL, paramData, headers, fileDirectory='', aFileName='', timeout=5):
#路径自行处理
rootPath = r"d:/"
if method.lower() == 'post-file':
method = "post"
# 注意这里没有做校验, 可能报错
headers.pop("Content-Type")
paramValues = list(paramData.values())
# 附件中间文件夹路径
fileDirectory = fileDirectory if '' != fileDirectory else paramValues[-1]
# 附件名称
aFileName = aFileName if '' != aFileName else paramValues[-2]
filePath = os.path.join(rootPath, fileDirectory.strip().strip('/'), aFileName.strip().strip('/'))
with open(filePath, 'rb') as fp:
# 复杂的文件请求: 文件名称, 字节流, 文件类型, 请求头
files = {'file': (aFileName, fp, 'application/octet-stream', {'Expires': '0'})}
# files = {'file': (aFileName, fp)}
getResponse = requests.request(method, targetURL,
json=paramData, files=files,
headers=headers, timeout=timeout)
else:
getResponse = requests.request(method, targetURL, json=paramData,
headers=headers, timeout=timeout)
return getResponse