Python requests post实现流式上传文件,带表单数据


Python requests post实现流式上传文件,带表单数据

标签:Python requests requests.toolbelt https接口测试 ssl认证
数据如下图
Content-type: application/octet-stream 流式上传
Python requests post实现流式上传文件,带表单数据_第1张图片

代码如下:

# -*- coding: utf-8 -*-
import json
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

url = 'https://xxxxxx.port'
# 登录获取token
auth = {"username": "admin", "password": "1"}
login_header = {"Content-Type": "application/json"}
login_url = url + "/auth"
login_post = requests.post(login_url, data=json.dumps(auth), headers=login_header, verify=False)
token = login_post.json().get('token').strip()

#上传流式文件

image_url=url+'/api/isssss/'
filename='fc_41_ssssss.rrr'
filepath='c:/fc_41_ssssss.rrr

with open(filepath,'rb') as f_:
    m= MultipartEncoder(
        fields={'storage':'distributed','name':'test123459956','disk_format':'rrr',
        'image_file':(filename,f_,'application/octet-stream')}
        )
    
    response=requests.post(
    	image_url,
    	headers={'Content-Type': m.content_type,'Authorization':'Bearer '+token},
    	data=m,
    	timeout=None, 
    	verify=False
    	)
    print m.content_type
print response.text


上传流式文件使用到了 requests.toolbelt 工具,这是参考地址
https://toolbelt.readthedocs.io/en/latest/uploading-data.html#streaming-multipart-data-encoder

post上传文件的参考地址:
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

说明 :
verify=False 是用来忽略ssl认证用的。
Timeout=None 无超时时间

你可能感兴趣的:(python接口测试)