关于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证书 就不在这里介绍了。 可能有时间再单独开一篇来写。

 

转载于:https://www.cnblogs.com/piperck/p/5076424.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值