我需要在python中使用HTTP PUT上传一些数据到服务器。从我对urllib2文档的简要阅读来看,它只执行HTTP POST。有没有办法在python中做一个HTTP PUT ?
当前回答
一个更合适的处理请求的方法是:
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
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)
这在python3中做得更好,并在stdlib文档中进行了记录
urllib.request.Request类获得一个方法=…参数。
一些示例用法:
req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')
urllib.request.urlopen(req)
你看过put.py吗?我以前用过。你也可以用urllib修改你自己的请求。
您可以使用请求库,与采用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简单得多,但确实需要安装和导入这个额外的包。