Requests-ssl-certification
提供:Dev Guides
リクエスト-SSL証明書
SSL証明書は、安全なURLに付属するセキュリティ機能です。 リクエストライブラリを使用すると、指定された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 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 paramを使用してパスを指定することで検証することもできます。
例
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"
}
}
]