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

有帮助吗?

解决方案

我过去使用过各种python HTTP库,我已经确定了'请求'作为我的最爱。现有的libs具有相当可用的接口,但是对于简单的操作,代码最终可能只有几行。请求中的基本PUT如下所示:

payload = {'username': 'bob', 'email': 'bob@bob.com'}
>>> r = requests.put("http://somedomain.org/endpoint", data=payload)

然后,您可以使用以下方法检查响应状态代码:

r.status_code

或回复:

r.content

请求有很多共同的糖和快捷方式,可以让你的生活更轻松。

其他提示

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)

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

您应该查看 httplib模块。它应该让你做出你想要的任何类型的HTTP请求。

我需要在一段时间内解决这个问题,以便我可以充当RESTful API的客户端。我决定使用httplib2,因为它允许我除了GET和POST之外还发送PUT和DELETE。 Httplib2不是标准库的一部分,但您可以从奶酪店轻松获取它。

您可以使用请求库,与采用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 类在python3中获得了 method = ... 参数。

一些示例用法:

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

我还建议Joe Gregario httplib2 。我在标准库中经常使用它而不是httplib。

您是否看过 put.py ?我过去曾经用过它。您也可以使用urllib破解自己的请求。

您当然可以使用现有的标准库从套接字到调整urllib,从而使用现有的标准库。

http://pycurl.sourceforge.net/

“PyCurl是libcurl的Python接口。”

“libcurl是一个免费且易于使用的客户端URL传输库,...支持... HTTP PUT&quot;

&quot; PycURL的主要缺点是它是libcurl上的一个相对较薄的层,没有任何好的Pythonic类层次结构。这意味着除非您已经熟悉libcurl的C API,否则它的学习曲线会有些陡峭。 &QUOT;

如果你想留在标准库中,你可以继承 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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top