使用python urllib/urllib2发出一个http POST请求来上传文件

Yin*_*ong 13 python post http urllib urllib2

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

curl -F "file=@style.css" -F output=json http://jigsaw.w3.org/css-validator/validator
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

我从上面的代码中得到了HTTP Error 500.但是既然我的curl命令成功了,那我的python请求肯定有问题吗?

我对这个话题很陌生,如果菜鸟问题有很简单的答案或错误,请原谅我.在此先感谢您的所有帮助!

Wol*_*lph 10

我个人认为你应该考虑请求库发布文件.

url = 'http://jigsaw.w3.org/css-validator/validator'
files = {'file': open('style.css')}
response = requests.post(url, files=files)
Run Code Online (Sandbox Code Playgroud)

使用上传文件urllib2并非不可能,但任务非常复杂:http://pymotw.com/2/urllib2/#uploading-files


Yin*_*ong 10

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

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)
Run Code Online (Sandbox Code Playgroud)

  • @Vladius该文件将自动关闭,因为它用作上下文管理器.请参阅[with`语句]的文档(https://docs.python.org/2.7/reference/compound_stmts.html#with). (8认同)