tags:

views:

3674

answers:

7

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?

A: 

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.

William Keller
I don't really wanna use some random guys http library
Rory
+1  A: 

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. "

wnoise
I'm sure it would work, but I want something a bit more pythonic
Rory
+6  A: 

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

John Montgomery
Nice solution, quiet pythonic but a bit too close to the metal and involving writing a lot of other code already
Rory
+23  A: 
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)
Florian Bösch
Looks like a bit of a dirty hack, but it seems to work elegantly and completly
Rory
+5  A: 

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.

Mike
+2  A: 

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

Corey Goldberg
A: 

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
Spooles