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


当前回答

如果希望留在标准库中,可以继承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)

其他回答

你可以使用requests.request

import requests

url = "https://www.example/com/some/url/"
payload="{\"param1\": 1, \"param1\": 2}"
headers = {
  'Authorization': '....',
  'Content-Type': 'application/json'
}

response = requests.request("PUT", url, headers=headers, data=payload)

print(response.text)

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

一个更合适的处理请求的方法是:

import requests

payload = {'username': 'bob', 'email': 'bob@bob.com'}

try:
    response = requests.put(url="http://somedomain.org/endpoint", data=payload)
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    print(e)
    raise

如果HTTP PUT请求中出现错误,将引发异常。

当然,您可以在任何级别上使用现有的标准库,从套接字到调整urllib。

http://pycurl.sourceforge.net/

PyCurl是libcurl的Python接口。

libcurl是一个免费且易于使用的客户端URL传输库,…支持……HTTP PUT”

“PycURL的主要缺点是它相对于libcurl来说是一个相对较薄的层,没有任何漂亮的python类层次结构。这意味着它有一个陡峭的学习曲线,除非你已经熟悉libcurl的C API。”

这在python3中做得更好,并在stdlib文档中进行了记录

urllib.request.Request类获得一个方法=…参数。

一些示例用法:

req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')
urllib.request.urlopen(req)