问题:有没有办法在python中执行HTTP PUT

我需要使用PUTpython中的HTTP将一些数据上传到服务器。从我对urllib2文档的简短阅读中,它只能使用HTTP POST。有什么办法可以PUT在python中执行HTTP 吗?

I need to upload some data to a server using HTTP PUT in python. From my brief reading of the urllib2 docs, it only does HTTP POST. Is there any way to do an HTTP PUT in python?


回答 0

过去,我使用过各种python HTTP库,而我最喜欢的是“ Requests ”。现有的库具有相当有用的接口,但是对于简单的操作,代码最终可能会花几行时间。请求中的基本PUT如下所示:

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

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

r.status_code

或回应:

r.content

请求有很多语法和快捷方式,可以使您的生活更轻松。

I’ve used a variety of python HTTP libs in the past, and I’ve settled on ‘Requests‘ as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:

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

You can then check the response status code with:

r.status_code

or the response with:

r.content

Requests has a lot synactic sugar and shortcuts that’ll make your life easier.


回答 1

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)
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)

回答 2

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 seems like a cleaner choice.

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

回答 3

您应该看看httplib模块。它应该让您发出所需的任何HTTP请求。

You should have a look at the httplib module. It should let you make whatever sort of HTTP request you want.


回答 4

我有一阵子需要解决此问题,以便可以充当RESTful API的客户端。我选择了httplib2,因为它允许我除了GET和POST之外还发送PUT和DELETE。Httplib2不是标准库的一部分,但是您可以从奶酪店轻松获得它。

I needed to solve this problem too a while back so that I could act as a client for a RESTful API. I settled on httplib2 because it allowed me to send PUT and DELETE in addition to GET and POST. Httplib2 is not part of the standard library but you can easily get it from the cheese shop.


回答 5

您可以使用请求库,与采用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)

请参阅请求库快速入门。我认为这比urllib2简单得多,但确实需要安装和导入此附加软件包。

You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:

pip install requests

More on installing requests.

Then setup the put request:

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)

See the quickstart for requests library. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.


回答 6

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

urllib.request.Request班获得了method=...在python3参数。

一些示例用法:

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

This was made better in python3 and documented in the stdlib documentation

The urllib.request.Request class gained a method=... parameter in python3.

Some sample usage:

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

回答 7

我还推荐Joe Gregario提供的httplib2。我经常使用它,而不是标准库中的httplib。

I also recommend httplib2 by Joe Gregario. I use this regularly instead of httplib in the standard lib.


回答 8

您看过put.py吗?我过去曾经用过。您也可以使用urllib修改自己的请求。

Have you taken a look at put.py? I’ve used it in the past. You can also just hack up your own request with urllib.


回答 9

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

http://pycurl.sourceforge.net/

“ PyCurl是libcurl的Python接口。”

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

“ PycURL的主要缺点是它是libcurl上相对较薄的一层,没有任何不错的Pythonic类层次结构。这意味着除非您已经熟悉libcurl的C API,否则它的学习曲线就比较陡峭。”

You can of course roll your own with the existing standard libraries at any level from sockets up to tweaking urllib.

http://pycurl.sourceforge.net/

“PyCurl is a Python interface to libcurl.”

“libcurl is a free and easy-to-use client-side URL transfer library, … supports … HTTP PUT”

“The main drawback with PycURL is that it is a relative thin layer over libcurl without any of those nice Pythonic class hierarchies. This means it has a somewhat steep learning curve unless you are already familiar with libcurl’s C API. “


回答 10

如果要保留在标准库中,则可以子类化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)

If you want to stay within the standard library, you can subclass 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)

回答 11

一个更合适的方法requests是:

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请求中存在错误,则会引发异常。

A more proper way of doing this with requests would be:

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

This raises an exception if there is an error in the HTTP PUT request.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。