如何将.netrc文件附加到python请求get方法?

2024-04-28 19:21:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python请求登录到一个站点。通常我在cmd中使用curl来完成这项工作

curl -c <path/urs_cookies.txt> -n -L https://site_FileUpload/login

其中-n在cwd中搜索包含我的用户名和密码的.netrc文件

但是,在python中使用

login = requests.get(url, auth=(username, password)) 

我相信这是因为我需要使用我的.netrc文件,而不是使用授权方法

我是否可以将此文件附加到我的登录请求中

非常感谢


Tags: 文件pathhttpstxtcmd站点sitelogin
2条回答

如果.netrc文件存在于主目录中,当未提供auth参数时,python请求将自动检查该文件在给定计算机(主机名)下的凭据

从请求文档https://2.python-requests.org/en/master/user/authentication/#netrc-authentication

If no authentication method is given with the auth argument, Requests will attempt to get the authentication credentials for the URL’s hostname from the user’s netrc file. The netrc file overrides raw HTTP authentication headers set with headers=.

If credentials for the hostname are found, the request is sent with HTTP Basic Auth.

假设您的主目录中有一个有效的.netrc文件,则以下操作应该可以正常工作https://www.labkey.org/Documentation/wiki-page.view?name=netrc

login = requests.get(url)

通过python请求库进行请求时,不需要传递.netrc文件。唯一的要求是.netrc文件应该在您的主目录中。我曾经通过python触发databricks作业,该作业需要.netrc文件中的所有凭据。我只是简单地使用了requests.post(url, data)并将我的.netrc文件保存在主目录中,它就可以工作了

相关问题 更多 >