python urllib2 post,使用python urllib / urllib2发出一个http 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

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)

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值