我需要在python中使用HTTP PUT上传一些数据到服务器。从我对urllib2文档的简要阅读来看,它只执行HTTP POST。有没有办法在python中做一个HTTP PUT ?


当前回答

您应该看看httplib模块。它应该允许您发出任何类型的HTTP请求。

其他回答

如果希望留在标准库中,可以继承urllib2。要求:

import urllib2

class RequestWithMethod(urllib2.Request):
    def __init__(self, *args, **kwargs):
        self._method = kwargs.pop('method', None)
        urllib2.Request.__init__(self, *args, **kwargs)

    def get_method(self):
        return self._method if self._method else super(RequestWithMethod, self).get_method()


def put_request(url, data):
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    request = RequestWithMethod(url, method='PUT', data=data)
    return opener.open(request)

Httplib似乎是一个更干净的选择。

import httplib
connection =  httplib.HTTPConnection('1.2.3.4:1234')
body_content = 'BODY CONTENT GOES HERE'
connection.request('PUT', '/url/path/to/put/to', body_content)
result = connection.getresponse()
# Now result.status and result.reason contains interesting stuff

我还推荐Joe Gregario编写的httplib2。我经常使用这个而不是标准库中的httplib。

不久前,我也需要解决这个问题,这样我才能充当RESTful API的客户端。我选择了httplib2,因为除了GET和POST之外,它还允许我发送PUT和DELETE。Httplib2不是标准库的一部分,但是您可以很容易地从奶酪商店获得它。

import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)