Python -- Curl works, requests lib doesn't
<p>This works from the command line:</p>

<pre><code> curl -H "Content-Type: application/json" -X POST -d '&lt;my data&gt;' http://my_user:my_pass@my_url
</code></pre>

<p>This doesn't work from a python script:</p>

<pre><code> res=requests.post(
  'http://my_user:my_pass@my_url',  
  json='&lt;my data&gt;')
</code></pre>

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

<pre><code>{"detail":"Invalid username/password."}
</code></pre>

<p><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/" rel="nofollow">http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/</a></p>

<p>Password includes these special characters % ( \ </p>

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

<p>I tried with <code>auth=('my_user','my_pass')</code> with the different escapes too.</p>

<p>I ran it through <a href="http://curl.trillworks.com/" rel="nofollow">http://curl.trillworks.com/</a> and still that didn't work.</p>

<p>Tomorrow I'm going to change my password to something simple and test.</p>

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

<p>You need to try setting the authentication using <code>requests</code> library like this:</p>

<pre><code>from requests.auth import HTTPBasicAuth

response = requests.post(url, json=payload, auth=HTTPBasicAuth('user', 'pass'))
</code></pre>

<p><a href="http://docs.python-requests.org/en/master/user/authentication/#basic-authentication" rel="nofollow">http://docs.python-requests.org/en/master/user/authentication/#basic-authentication</a></p>

python curl django-rest-framework python-requests pycurl