基于 Requests 中的 cookie 的持久会话

Persisten session based on cookies in Requests

为什么我的会话在完成后仍要我进行身份验证?

def main(pswd):
    with session() as s:
        s.post('url',
               auth=('user', pswd),
              )

        response = s.get('url2', cookies=s.cookies)

        print(response.text)

为什么我的会话不持久?

之后控制台正在打印:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>

我也能做到:

s.get('url', auth=('user', 'login')).text

这会起作用,但对于第二个 s.get 它将不起作用。我必须再通过一次凭据。

在请求中使用 Session object 时,您可以按如下方式设置身份验证详细信息:

with session() as s:
    s.auth = ('user', 'pass')
    s.post(url)  # auth headers will be sent with this request
    s.post(url2)  auth headers will be sent with this request as well