¿Hay alguna manera de hacer HTTP PUT en python


Necesito subir algunos datos a un servidor usando HTTP PUT en python. De mi breve lectura de los documentos urllib2, solo hace HTTP POST. ¿Hay alguna manera de hacer un HTTP PUT en python?

Author: Jason Orendorff, 2008-09-22

11 answers

He utilizado una variedad de bibliotecas HTTP python en el pasado, y me he establecido en ' Peticiones' como mi favorito. Las libs existentes tenían interfaces bastante utilizables, pero el código puede terminar siendo unas pocas líneas demasiado largas para operaciones simples. Un PUT básico en las solicitudes se ve como:

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

Luego puede verificar el código de estado de la respuesta con:

r.status_code

O la respuesta con:

r.content

Requests tiene mucho azúcar sináctico y atajos que te harán la vida más fácil.

 282
Author: John Carter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-24 15:54:13
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)
 234
Author: Florian Bösch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-21 20:24:21

Httplib parece una opción más limpia.

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
 45
Author: Spooles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-12 22:13:42

Debería echar un vistazo al módulo httplib . Debería permitirle hacer cualquier tipo de solicitud HTTP que desee.

 8
Author: John Montgomery,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-21 20:18:57

Tuve que resolver este problema también hace un tiempo para poder actuar como cliente para una API RESTful. Me decidí por httplib2 porque me permitía enviar PUT y DELETE además de GET y POST. Httplib2 no es parte de la biblioteca estándar, pero puede obtenerla fácilmente en la tienda de quesos.

 8
Author: Mike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-22 12:46:40

Puede usar la biblioteca de solicitudes, simplifica mucho las cosas en comparación con el enfoque urllib2. Primero instalarlo desde pip:

pip install requests

Más sobre instalación de solicitudes.

Luego configura la solicitud 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)

Consulte la biblioteca de inicio rápido para solicitudes. Creo que esto es mucho más simple que urllib2, pero requiere que este paquete adicional se instale e importe.

 8
Author: radtek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-22 20:23:01

También recomiendo httplib2 de Joe Gregario. Uso esto regularmente en lugar de httplib en la librería estándar.

 6
Author: Corey Goldberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-05 17:26:40

Esto fue mejorado en python3 y documentado en la documentación de stdlib

La clase urllib.request.Request ganó un parámetro method=... en python3.

Algunos ejemplos de uso:

req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')
urllib.request.urlopen(req)
 4
Author: Anthony Sottile,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-08 03:56:05

¿Has echado un vistazo a put.py ? Lo he usado en el pasado. También puede hackear su propia solicitud con urllib.

 3
Author: William Keller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-21 20:12:49

Por supuesto, puede rodar su propio con las bibliotecas estándar existentes en cualquier nivel desde sockets hasta ajustar urllib.

Http://pycurl.sourceforge.net/

"PyCurl es una interfaz Python para libcurl."

"libcurl es una biblioteca de transferencia de URL del lado del cliente gratuita y fácil de usar, ... apoyo ... HTTP PUT "

"El principal inconveniente con PycURL es que es una capa relativamente delgada sobre libcurl sin ninguna de esas buenas jerarquías de clases pitónicas. Esto significa que tiene una curva de aprendizaje algo empinada a menos que ya esté familiarizado con la API C de libcurl. "

 2
Author: wnoise,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-21 21:17:24

Si desea permanecer dentro de la biblioteca estándar, puede subclase 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)
 2
Author: Wilfred Hughes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-27 13:19:55