efultz
efultz

Reputation: 1267

Python requests call not handling authentication as expected

I have a list in which I am putting the url and authentication parameters for a requests get call. If I try the call this way I get authentication error (401) but if I break out the auth by itself explicitly on the call things work. Why can't I include auth in this manner and expect it to properly "explode" in the call?

parms = []
parms.append(url)
parms.append('auth=(''UID'', ''PWD'')')
response = requests.get(*parms) 

This results in 404 because it is not recognizing the authentication. BUT, if I do this it works. To me these seem the same. The single quotes are only different to get the string to append in the list properly. I thought the first way would result in 2 parameters - url and auth

parms = []
parms.append(url)
response = requests.get(*parms, auth=('UID', 'PWD')) 

Upvotes: 1

Views: 219

Answers (1)

Paulo Scardine
Paulo Scardine

Reputation: 77389

The first one is equivalent to the following:

requests.get(url, "auth=('UID', 'PWD')")

When you really want:

requests.get(url, auth=('UID', 'PWD'))

You must use this instead:

args = []
kwargs = {}

args.append(url)
kwargs['auth'] = ('UID', 'PWD')

requests.get(*args, **kwargs)

The rule is:

  • when you have function(foo, bar) you are using positional parameters, they go into *args.
  • when you have function(foo=1, bar=2) you are using named parameters, they go into **kwargs.
  • you can mix both, in Python 2 positional parameters must be placed before named parameters.

Upvotes: 2

Related Questions