newbie question: urllib2.urlopen

Posted on
Sat Mar 19, 2016 8:48 pm
roquej offline
User avatar
Posts: 609
Joined: Jan 04, 2015
Location: South Florida, USA

newbie question: urllib2.urlopen

Sorry for the questions, but struggling with this simple problem.

If the required curl syntax is:

"curl --user <my_username>:<my_password> https://data.tankutility.com/api/getToken"

How would you translate to the correct syntax for urlib2.urlopen? I tried a few combinations of the following without success

urlReturned = urllib2.urlopen('https://data.tankutility.com/api/getToken?user=*username:password*&device=*token_name*')

Thank you in advance.

JP

Posted on
Sun Mar 20, 2016 6:51 am
FlyingDiver offline
User avatar
Posts: 7217
Joined: Jun 07, 2014
Location: Southwest Florida, USA

Re: newbie question: urllib2.urlopen

It's not that simple. curl is doing a bunch of work behind the scenes. Here's the official way to do it:

https://docs.python.org/2/howto/urllib2.html#id6

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Posted on
Sun Mar 20, 2016 7:59 am
roquej offline
User avatar
Posts: 609
Joined: Jan 04, 2015
Location: South Florida, USA

Re: newbie question: urllib2.urlopen

Thank you. Have a lot of homework to do...

JP

Posted on
Sun Mar 20, 2016 8:03 am
FlyingDiver offline
User avatar
Posts: 7217
Joined: Jun 07, 2014
Location: Southwest Florida, USA

Re: newbie question: urllib2.urlopen

You might want to look at the Requests library, rather than using urllib2. It's easier.

http://docs.python-requests.org/en/master/

joe (aka FlyingDiver)
my plugins: http://forums.indigodomo.com/viewforum.php?f=177

Posted on
Mon Mar 21, 2016 10:10 am
roquej offline
User avatar
Posts: 609
Joined: Jan 04, 2015
Location: South Florida, USA

Re: newbie question: urllib2.urlopen

Joe,

Thank you for pointing me in the right direction. I wasn't able to use the request api. Kept getting errors. However, I was able to solve my problem as below, just in case it helps the next newbie.

import simplejson as json
import urllib2
from base64 import b64encode

#get token
url='XXXX'
request = urllib2.Request(url)
request.add_header('Authorization', 'Basic ' + b64encode(user + ':' + pass))

#get TOKEN in json from api url
urlReturned = urllib2.urlopen(request)

#format api returned data
data_getStatus = urlReturned.read()

#interpret json
data = json.loads(data_getStatus)

#get json variables to python variables
variable=data[u'YYY']

JP

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 19 guests