我需要使用Python中的HTTP PUT
方法将一些数据上传到服务器。从我简短阅读urllib2
文档的了解,它只支持HTTP POST
。
是否有办法在Python中执行HTTP PUT
操作?
我过去使用过各种Python HTTP库,最终我选择了requests作为我的首选。现有的库具有相当可用的接口,但对于简单操作而言,代码可能会变得过长。使用requests进行基本的PUT请求如下:
payload = {'username': 'bob', 'email': 'bob@bob.com'}
>>> r = requests.put("http://somedomain.org/endpoint", data=payload)
您可以使用以下代码检查响应状态码:
r.status_code
或使用以下响应:
r.content
Requests提供了很多语法糖和快捷方式,这些可以让你的生活更加轻松。
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)
urllib2.urlopen
而不是opener.open
。 - XiaoHttplib似乎是一个更干净的选择。
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
您可以使用requests库,与采用urllib2方法相比,它能够使许多事情变得简单。首先从pip安装它:
pip install requests
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)
请查看Requests库快速入门指南。相比urllib2,我认为这个库更加简单易用,但需要安装并导入额外的包。
这在Python3中得到了改进,并在标准库文档中有所记录。
urllib.request.Request
类在Python 3中增加了一个method = ...
参数。
一些示例用法:
req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')
urllib.request.urlopen(req)
我曾经也需要解决这个问题,以便我可以作为RESTful API的客户端。最终我选择了httplib2,因为它不仅支持GET和POST请求,还支持PUT和DELETE请求。虽然httplib2不是Python标准库的一部分,但你可以很容易地从cheese shop获取它。
你看过 put.py 了吗?我之前用过它。你也可以使用 urllib 编写自己的请求。
如果您想保持在标准库中,您可以继承urllib2.Request
:
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)
json=payload
参数。 - ManuelSchneid3r