前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 模拟post上传图片

python 模拟post上传图片

作者头像
py3study
发布2020-01-07 22:23:36
1.9K0
发布2020-01-07 22:23:36
举报
文章被收录于专栏:python3python3python3

python  模拟post上传图片

小编在最近在学习用 python 做接口测试,其中有个上传图片的接口,在网上各种搜索,各种尝试。下面是我慢慢摸索的过程,希望能帮助大家(ps:新手编写,欢迎拍砖)

1.使用poster第三方模块

如果要使用poster 则需要先 安装poster,这个方法虽然成功了 ,但我其他接口使用的是requests 和urllib2的交互出现了问题(我没有找到解决办法Σ( ° △ °|||)︴)

主要代码:

# test_client.py

from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2

# 在 urllib2 上注册 http 流处理句柄
register_openers()

# 开始对文件 "DSC0001.jpg" 的 multiart/form-data 编码
# "image1" 是参数的名字,一般通过 HTML 中的 <input> 标签的 name 参数设置

# headers 包含必须的 Content-Type 和 Content-Length
# datagen 是一个生成器对象,返回编码过后的参数
datagen, headers = multipart_encode({"image1": open("DSC0001.jpg", "rb")})

# 创建请求对象
request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers)
# 实际执行请求并取得返回
print urllib2.urlopen(request).read()

2. 使用Python Requests上传表单数据和文件

主要代码:

data = {    'name': 'nginx'}
files = {'file': open("abc.csv", 'rb')}
response = requests.post(url, data=data, files=files)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • python  模拟post上传图片
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档