2

Is it posisble to adapt this piece of code for make put request:

#!/usr/bin/python

import urllib2, base64, urllib

dir="https://domain.com/api/v1/"
use="one@two.com"
pas="123456"

base64string = base64.encodestring('%s:%s' % (use, pas)).replace('\n', '')

request = urllib2.Request(dir, headers={"Authorization" : "Basic %s" % base64string})
response = urllib2.urlopen(request).read()

print response

I try with this other code, but I think that it do a get request, isn't it?

#!/usr/bin/python

import urllib2, base64, urllib

dir="https://domain.com/api/v1/"
use="one@two.com"
pas="123456"

values = {
      'list' :["201.22.44.12","8.7.6.0/24"]
    }

data = urllib.urlencode(values)

base64string = base64.encodestring('%s:%s' % (use, pas)).replace('\n', '')

request = urllib2.Request(dir, data, headers={"Authorization" : "Basic %s" % base64string})
response = urllib2.urlopen(request).read()
rfmoz
  • 991
  • 4
  • 14
  • 27

1 Answers1

8

I am not sure It will work or not for you but check this piece of code

You can encode a dict using urllib like this:

import urllib
import urllib2

url = 'http://example.com/...'
values = { 'productslug': 'bar','qty': 'bar' }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()
print result
Ashish Jain
  • 760
  • 1
  • 8
  • 23
  • Yes, this work, but the only problem is with the urlencode, wich, in my case, produce an error in the request. – rfmoz Jun 17 '13 at 15:43
  • check the values which is coming in dictionary format or not and can u tell me what error is coming – Ashish Jain Jun 19 '13 at 10:17
  • 1
    for my case, i don't need urlencode. but for additional information, if the response is in gzip format, for print you need this: `if response.info().get('Content-Encoding') == 'gzip': buf = StringIO( response.read()) f = gzip.GzipFile(fileobj=buf) data = f.read() # Imprimir bonito print json.dumps(json.loads(data), sort_keys = True, indent = 2)` – rfmoz Jun 19 '13 at 13:41