stampede76
stampede76

Reputation: 1631

Python -- Curl works, requests lib doesn't

This works from the command line:

 curl -H "Content-Type: application/json" -X POST -d '<my data>' http://my_user:my_pass@my_url

This doesn't work from a python script:

 res=requests.post(
  'http://my_user:my_pass@my_url',  
  json='<my data>')

What happens is it hits the server, but doesn't authorize. The REST API is built with Django Rest Framework, and I get

{"detail":"Invalid username/password."}

http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/

Password includes these special characters % ( \

I escaped \ , so it's a double backslash. I also tried with r in front of string, and 4 backslashes.

I tried with auth=('my_user','my_pass') with the different escapes too.

I ran it through http://curl.trillworks.com/ and still that didn't work.

Tomorrow I'm going to change my password to something simple and test.

If that doesn't work, I'm giving up and adding a bash script at the end that just runs that curl command.

Upvotes: 1

Views: 709

Answers (2)

stampede76
stampede76

Reputation: 1631

I escaped \ , so it's a double backslash. I also tried with r in front of string, and 4 backslashes.

The \ in the curl command was to escape a parenthesis. It wasn't part of the password.

I removed it and now it works.

Upvotes: 0

karthikr
karthikr

Reputation: 99620

You need to try setting the authentication using requests library like this:

from requests.auth import HTTPBasicAuth

response = requests.post(url, json=payload, auth=HTTPBasicAuth('user', 'pass'))

http://docs.python-requests.org/en/master/user/authentication/#basic-authentication

Upvotes: 2

Related Questions