Search code examples
pythonpython-3.xpython-requestsconfiguration-fileshttp-error

Strange issue with python requests.get method


Oh Brother!, I have been scratching my head over this for past two hours. Finally I decided to turn this over to mighty powers at stackoverflow. ye o python warriors, please help

This works :

requests.get('https://abc.123.xyz.xom/getmethisurl',
             auth=('PasswordIsAuthToken', 'khcdhk-dcbdmsb-dcbdsm-aBSDCXKN'),
             verify=False)

This doesn't, getting a 401 every time :

defconn.py

import json
import requests
from requests.auth import HTTPBasicAuth


class connect(object):

    def __init__(self, url, user, token):
        self.url=url
        self.user=user
        self.token=token

    def uget(self, uri):
        self.url = self.url + uri

        ## EDIT 1 : Code added to print out the parameters values and type for debugging
        print ("IN:", repr(self.url), repr(self.user), repr(self.token))
        print(self.url, type(self.url))
        print(self.user, type(self.user))
        print(self.token, type(self.token))

        res=requests.get(self.url, auth=(self.user, self.token), verify=False)
        if res.status_code == 401:
           print ("ERORR 401 !!!!")
        else:
           return res

app.py (This is the main script)

import defconn
from connexion.resolver import RestyResolver

props = dict(line.strip().split('=') for line in open('env.properties'))

url=props['connect.url']
user=props['connect.username']
token=props['connect.token']

oj=defconn.connect(url,user,token)
oj.uget('/getmethisurl')

Here is my env.properties :

env.properties

connect.url=https://abc.123.xyz.xom
connect.username=PasswordIsAuthToken
connect.token=khcdhk-dcbdmsb-dcbdsm-aBSDCXKN

Output

output

Any help is greatly appreciated.

Edit 1 : Adding the diagnostic code as well as its output screenshot too

Thanks - A


Solution

  • The likely cause is that somewhere along the way the parameters don't match the simple hard-code example. Try adding a diagnostic line so that you can isolate the problem:

    class connect(object):
    
        def __init__(self, url, user, token):
            self.url=url
            self.user=user
            self.token=token
    
        def uget(self, uri):
            self.url = self.url + uri
            print(repr(self.url), repr(self.user), repr(self.token)) # <== DIAGNOSTIC
            res=requests.get(self.url, auth=(self.user, self.token), verify=False)
            if res.status_code == 401:
               print ("ERORR 401 !!!!")
            else:
               return res
    

    As noted in the comments, the self.url = self.url + uri probably isn't what you want. Instead, just update a local variable.