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


当前回答

使用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

其他回答

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

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

您可以使用请求库,与采用urllib2方法相比,它简化了很多事情。首先从pip安装它:

pip install requests

更多关于安装请求的信息。

然后设置put请求:

import requests
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

# Create your header as required
headers = {"content-type": "application/json", "Authorization": "<auth-key>" }

r = requests.put(url, data=json.dumps(payload), headers=headers)

请参阅请求库的快速入门。我认为这比urllib2简单得多,但确实需要安装和导入这个额外的包。

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

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

一些示例用法:

req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')
urllib.request.urlopen(req)
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)