我用的是mac电脑,之前在用langchain,我想看下发送给openai 的请求具体是什么样子的,所有就想着安装一个抓包工具,然后设置代理,在抓包工具上面看具体的http请求。
结果浏览器的http和https请求和手机端的http和https请求都能抓到了,就是python 代码里面https请求报错,
后面查了很久,知道了原因,mac下面的python 没有用系统的根证书,用的是自己python 包里面的根证书,所以就算你把抓包工具的根证书安装到系统钥匙串也没有,人家python 根本不用这里的所以就用了其他方法
安装certifi
pip install certifi
下载抓包工具的根证书,然后把它和其他机构根证书和在一起
import certifi with open('Ca.pem', 'wb') as combined_cert_file: with open(certifi.where(), 'rb') as certifi_cert: combined_cert_file.write(certifi_cert.read()) with open('./reqable-ca.crt', 'rb') as your_cert: combined_cert_file.write(your_cert.read())
python 工具用新的根证书
import os import requests # 设置代理 os.environ['http_proxy'] = 'http://10.0.89.247:9000' os.environ['https_proxy'] = 'http://10.0.89.247:9000' # 直接请求报错 [SSL: CERTIFICATE_VERIFY_FAILED] # response = requests.get('https://www.baidu.com') # print(response.text) # 设置环境变量REQUESTS_CA_BUNDLE为指定的CA证书文件路径 # 现在发送请求,requests将使用上述指定的CA证书进行SSL验证 os.environ['REQUESTS_CA_BUNDLE'] = "/Users/chengqian/Desktop/aigc_video/Ca.pem" response = requests.get('https://www.baidu.com') print(response.text)
异步http没法全局设置
import aiohttp import ssl import asyncio class Fetcher: def __init__(self, proxy_url, certfile_path): self.proxy_url = proxy_url self.ssl_context = ssl.create_default_context(cafile=certfile_path) async def fetch(self, url): async with aiohttp.ClientSession() as session: async with session.get(url, proxy=self.proxy_url, ssl=self.ssl_context) as response: print(await response.text()) proxy_url = "http://10.0.89.247:9000" certfile_path = "/Users/chengqian/Desktop/aigc_video/Ca.pem" fetcher = Fetcher(proxy_url, certfile_path) asyncio.run(fetcher.fetch("https://www.baidu.com"))