我应该使用带有 p12 证书的会话吗

Should I use a session with p12-certificate

所以我写了一个使用 requests_pkcs12-library 和 .p12-cert.

的爬虫

目前我在按照文档中的描述使用它的地方提出了很多请求

from requests_pkcs12 import get

r = get('https://example.com/test', pkcs12_filename='clientcert.p12', pkcs12_password='correcthorsebatterystaple') 

文档还显示您可以在会话中使用它。

from requests import Session 
from requests_pkcs12 import Pkcs12Adapter 

session = Session()
session.mount('https://example.com', Pkcs12Adapter(pkcs12_filename='clientcert.p12', pkcs12_password='correcthorsebatterystaple')) 
r = session.get('https://example.com/test')

所以这也很好用。但是这样做有什么好处呢?它是否降低了它所验证的服务器的压力?

它似乎没有向会话添加经过身份验证的 cookie,所以我想知道为什么一个比另一个更受欢迎。

有人知道吗?

提前致谢

是的,使用会话可以提高客户端的性能并减少服务器端的负载。

请注意,这与 requests_pkcs12 库几乎无关,而是 requests 库的通用机制。

requests manual 状态:

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3’s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

HTTP persistent connection 的链接维基百科条目指出:

Advantages

  • ...
  • Reduced CPU usage and round-trips because of fewer new connections and TLS handshakes.

TLS handshakes 上的维基百科部分指出:

Client-authenticated TLS handshake

...

  1. Negotiation Phase:
    • ...
    • The server sends a CertificateRequest message, to request a certificate from the client so that the connection can be mutually authenticated.
    • ...
    • The client responds with a Certificate message, which contains the client's certificate.

总而言之,使用 requests 会话会导致连接池,从而导致更少的 TCP 连接,从而减少 TLS 握手,这反过来意味着更少的客户端证书身份验证。请注意,这与客户端证书如何提供给 requests 无关,无论是 PKCS12 格式(使用 requests_pkcs12)还是 PEM 格式(使用普通 requests)。