如何使用用户名和密码的特定变量发送请求后身份验证?

2024-03-29 10:14:25 发布

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

我正在尝试使用带有companyIdaccountPassword变量的auth发送请求后身份验证,但如果使用auth方式,则无法进行身份验证

下面的工作,但我不能使用URL中的用户名和密码作为其创建的用户名和密码存储在日志中的安全问题

url = AUTH_URI + '/' + dyn_url + "?appIdKey=" + str.encode(APP_ID_KEY) + "&companyId=" + self._user + "&accountPassword=" + self._pswd
                r2 = requests.post(url,timeout=DEFAULT_REQUESTS_TIMEOUT,headers={'Content-Type': 'application/json;charset=UTF-8'},allow_redirects=False)

将其更改为使用auth变量无法进行身份验证,有关如何修复此问题的任何指导

            url = AUTH_URI + '/' + dyn_url + "?appIdKey=" + str.encode(APP_ID_KEY)
            r2 = requests.post(url,timeout=DEFAULT_REQUESTS_TIMEOUT,headers={'Content-Type': 'application/json;charset=UTF-8'},auth=('companyId=self._user','accountPassword=self._pswd'),allow_redirects=False)

我得到以下错误,不知何故'companyId=self._user','accountPassword=self._pswd'没有生效

错误:-

Please enter the username and password

Tags: selfauth身份验证url密码uri用户名dyn
1条回答
网友
1楼 · 发布于 2024-03-29 10:14:25

您正在发送字符串literal'self._user'作为用户名。如果正在运行Python 3.6或更高版本,请尝试使用f-strings

r2 = requests.post(url,
    timeout=DEFAULT_REQUESTS_TIMEOUT,
    headers={'Content-Type': 'application/json;charset=UTF-8'},
    auth=(f'companyId={self._user}',
          f'accountPassword={self._pswd}'),
    allow_redirects=False)

编辑:对于Python 2.7,它将是:

r2 = requests.post(url,
    timeout=DEFAULT_REQUESTS_TIMEOUT,
    headers={'Content-Type': 'application/json;charset=UTF-8'},
    auth=('companyId={}'.format(self._user),
          'accountPassword={}'.format(self._pswd)),
    allow_redirects=False)

相关问题 更多 >