python模拟上传图片_python如何模拟含有文件上传的表单

展开全部

在机器上安装了 Python 的

setuptools,可以通过下面的命令来安装 poster:easy_install poster

装完之后,就可以像用下面代码模拟上传文件表单了:e69da5e6ba9062616964757a686964616f31333337396332from poster.encode import multipart_encode

from poster.streaminghttp import register_openers

import urllib2

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

register_openers()

# 开始对文件 "DSC0001.jpg" 的 multiart/form-data 编码

# "image1" 是参数的名字,一般通过 HTML 中的  标签的 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()