關於python requests 包跑ssl的設置 和 charles相關抓包的問題


由於在測試服務器上測試東西都是https,然后最近又在和大神一起開發openapi,api寫好當然是要測試的

python上測試接口最好用的莫過於requests模塊了。但是 我還從來沒有用requests模塊過ssl 在網上找了一些資料看到說的是,使用一個urllib3的模塊。

好吧進入正題。

r = requests.post(url, data=payload, proxies=proxies, verify=True)

這行代碼 增加了兩個平時不怎么用得上的字段。 proxies 和 verify 。 proxies 一會兒介紹 verify 是requests包是對目標網站啟用證書驗證的選項。這里

摘抄文檔里的相關內容。

SSL Cert Verification
Requests can verify SSL certificates for HTTPS requests, just like a web browser. To check a host’s SSL certificate, you can use the verify argument:

>>> requests.get('https://kennethreitz.com', verify=True)
requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'
I don’t have SSL setup on this domain, so it fails. Excellent. GitHub does though:

>>> requests.get('https://github.com', verify=True)
<Response [200]>
You can pass verify the path to a CA_BUNDLE file or directory with certificates of trusted CAs:

>>> requests.get('https://github.com', verify='/path/to/certfile')
This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable.

Requests can also ignore verifying the SSL certificate if you set verify to False.

>>> requests.get('https://kennethreitz.com', verify=False)
<Response [200]>
By default, verify is set to True. Option verify only applies to host certs.

You can also specify a local cert to use as client side certificate, as a single file (containing the private key and the certificate) or as a tuple of both file’s path:

>>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))
<Response [200]>
If you specify a wrong path or an invalid cert:

>>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')
SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_

官網提供了這些用法使用 里面包括在 電腦上已經安裝了受信證書,直接使用verify=True進行設置 就能正常訪問ssl 以及沒有安裝相應證書 需要對該字段進行路徑指定。以及直接將verify=False 不進行校驗。

這里由於我的電腦上是有公司的測試服務器證書的,所以要進行ssl校驗只需要將verify字段置為True就可以正常請求和訪問了。這里有個問題要特別注意一下,也是我遇到的問題,因為當時我使用requests這個包比較早。所以當時pip install下載的還是一個1.x的版本,這個版本的ssl校驗就有點問題。建議大家在使用之前先將模塊更新到最新的版本再進行操作。避免不必要的錯誤。

 

好了 到了這里還沒完,由於api請求最大的問題就是調試。所以抓包當然是必不可少。在更新了新版的requests之后,charles是沒有辦法抓到requests包的。他就着么莫名其妙從charles的監聽下面溜走了。 這里就需要設置requests的代理,將http 和https的代理字段都指向charles的代理地址 默認是 本地的8888端口 然后將這個字段傳給proxies  

proxies = {
  "http": "localhost:8888",
  "https": "localhost:8888",
}

就可以正常請求了! 這里要抓去https的包 還需要配置charles證書 就不在這里介紹了。 可能有時間再單獨開一篇來寫。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM