使用python urllib / urllib2发出一个http POST请求来上传文件 [英] Make an http POST request to upload a file using python urllib/urllib2

查看:3495
本文介绍了使用python urllib / urllib2发出一个http POST请求来上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发一个POST请求,使用python将文件上传到Web服务(并获得响应)。例如,我可以使用 curl 执行以下POST请求:

I would like to make a POST request to upload a file to a web service (and get response) using python. For example, I can do the following POST request with curl:

curl -F "file=@style.css" -F output=json http://jigsaw.w3.org/css-validator/validator

如何使用python urllib / urllib2发出相同的请求?到目前为止我最接近的是:

How can I make the same request with python urllib/urllib2? The closest I got so far is the following:

with open("style.css", 'r') as f:
    content = f.read()
post_data = {"file": content, "output": "json"}
request = urllib2.Request("http://jigsaw.w3.org/css-validator/validator", \
                          data=urllib.urlencode(post_data))
response = urllib2.urlopen(request)

我从上面的代码中得到了HTTP错误500。但是由于我的 curl 命令成功,我的python请求一定有问题吗?

I got a HTTP Error 500 from the code above. But since my curl command succeeds, it must be something wrong with my python request?

我很新这个话题,请原谅我,如果菜鸟问题有非常简单的答案或错误。提前感谢您的所有帮助!

I am quite new to this topic and please forgive me if the rookie question has very simple answers or mistakes. Thanks in advance for all your helps!

推荐答案

经过一番挖掘,似乎这篇文章解决了我的问题。事实证明我需要正确设置多部分编码器。

After some digging around, it seems this post solved my problem. It turns out I need to have the multipart encoder setup properly.

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

register_openers()

with open("style.css", 'r') as f:
    datagen, headers = multipart_encode({"file": f})
    request = urllib2.Request("http://jigsaw.w3.org/css-validator/validator", \
                              datagen, headers)
    response = urllib2.urlopen(request)

这篇关于使用python urllib / urllib2发出一个http POST请求来上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆