简体   繁体   English

Python — Curl有效,请求lib不起作用

[英]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: 这不适用于python脚本:

 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 REST API是使用Django Rest Framework构建的,我得到了

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

http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/ 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. 我也尝试在字符串前面加上r和4个反斜杠。

I tried with auth=('my_user','my_pass') with the different escapes too. 我也尝试了auth=('my_user','my_pass')和不同的转义auth=('my_user','my_pass')

I ran it through http://curl.trillworks.com/ and still that didn't work. 我通过http://curl.trillworks.com/运行了它,但仍然没有用。

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. 如果那不起作用,我将放弃并在仅运行该curl命令的末尾添加一个bash脚本。

You need to try setting the authentication using requests library like this: 您需要尝试使用requests库设置身份验证,如下所示:

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 http://docs.python-requests.org/en/master/user/authentication/#basic-authentication

I escaped \\ , so it's a double backslash. 我逃脱了\\,所以它是两个反斜杠。 I also tried with r in front of string, and 4 backslashes. 我也尝试在字符串前面加上r和4个反斜杠。

The \\ in the curl command was to escape a parenthesis. curl命令中的\\是转义括号。 It wasn't part of the password. 它不是密码的一部分。

I removed it and now it works. 我将其删除,现在可以使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM