Skip to content

Instantly share code, notes, and snippets.

@limed
Created November 10, 2011 18:27
Show Gist options
  • Save limed/1355667 to your computer and use it in GitHub Desktop.
Save limed/1355667 to your computer and use it in GitHub Desktop.
Using PUT in urllib2
#!/usr/bin/python
import urllib2
import json
apikey = ''
user = ''
baseurl = ''
query_enable = { 'is_enabled' : True }
query_disable = { 'is_enabled' : False, 'disabled_reason' : "infringement3" }
url = baseurl + user + "?key=" + apikey
json_data = json.dumps(query_disable)
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(url, data=json_data)
request.add_header('Content-Type', 'application/json')
request.get_method = lambda: 'PUT'
url = opener.open(request)
print url.read()
@rootVIII
Copy link

rootVIII commented Feb 22, 2019

Thanks for that... Here it is with Basic Auth as well for to PUT JSON. The encodestring() variable may be outdated but your answer helped me on an old server with only Python 2.6 and no option to install requests.

from base64 import encodestring

def put_auth(self, url, username, password, data):
        opener = urllib2.build_opener(urllib2.HTTPHandler)
        req = urllib2.Request(url, data=json.dumps(data))
        auth_header = encodestring("%s:%s" % (u, p))[:-1]
        req.add_header('Content-Type', 'application/json')
        req.add_header('Authorization', 'Basic ' + auth_header)
        req.get_method = lambda: 'PUT'
        request = opener.open(req)
        self.status_code = request.getcode()
        return request.read()

@Punkoivan
Copy link

Hello guys, could you please explain why we're using lamda here for get_method()?
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment