Requests - SSL 证书



SSL 证书是一种随安全 URL 提供的安全特性。当你使用 Requests 库时,它还会验证给定的 https URL 的 SSL 证书。SSL 验证在请求模块中默认启用,并且在没有此证书时会引发错误。

使用安全 URL

以下是使用安全 URL 的示例 −

import requests
getdata = requests.get(https://jsonplaceholder.typicode.com/users)
print(getdata.text) 

输出

E:\prequests>python makeRequest.py
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "[email protected]",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
]

我们能轻松地从上述 https URL 获得响应,这是因为请求模块能够验证 SSL 证书。

只需添加 verify=False,你就可以禁用 SSL 验证,如下例所示。

示例

import requests
getdata = 
requests.get('https://jsonplaceholder.typicode.com/users', verify=False)
print(getdata.text)

你会得到输出,但它也会显示一条警告消息,即 SSL 证书未经验证,建议添加证书验证。

输出

E:\prequests>python makeRequest.py
connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is 
being made. Adding certificate verification is strongly advised. See: 
https://urllib3
.readthedocs.io/en/latest/advanced-usage.htm  l#ssl-warnings
 InsecureRequestWarning)
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret", 
      "email": "[email protected]",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered   client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
]

你还可以通过在你的终端托管 SSL 证书,然后使用 verify 参数指定路径,如下所示,验证 SSL 证书。

示例

import requests
getdata = 
requests.get('https://jsonplaceholder.typicode.com/users', verify='C:\Users\AppData\Local\certificate.txt')
print(getdata.text)  

输出

E:\prequests>python makeRequest.py
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "[email protected]",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered   client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
] 
广告