我需要在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)

其他回答

使用urllib3

为此,您需要在URL中手动编码查询参数。

>>> import urllib3
>>> http = urllib3.PoolManager()
>>> from urllib.parse import urlencode
>>> encoded_args = urlencode({"name":"Zion","salary":"1123","age":"23"})
>>> url = 'http://dummy.restapiexample.com/api/v1/update/15410' + encoded_args
>>> r = http.request('PUT', url)
>>> import json
>>> json.loads(r.data.decode('utf-8'))
{'status': 'success', 'data': [], 'message': 'Successfully! Record has been updated.'}

使用请求

>>> import requests
>>> r = requests.put('https://httpbin.org/put', data = {'key':'value'})
>>> r.status_code
200

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

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请求中出现错误,将引发异常。

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

你看过put.py吗?我以前用过。你也可以用urllib修改你自己的请求。

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

http://pycurl.sourceforge.net/

PyCurl是libcurl的Python接口。

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

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