Python使用指定端口进行http请求的例子

yipeiwu_com5年前Python基础

使用requests库

class SourcePortAdapter(HTTPAdapter):
 """"Transport adapter" that allows us to set the source port."""

 def __init__(self, port, *args, **kwargs):
  self.poolmanager = None
  self._source_port = port
  super().__init__(*args, **kwargs)

 def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
  self.poolmanager = PoolManager(
   num_pools=connections, maxsize=maxsize,
   block=block, source_address=('', self._source_port))

s = requests.Session()
s.mount('https://baidu.com', SourcePortAdapter(54321))
s.get('https://baidu.com')

我用wireshark测试发现是走的54321端口。

使用pycurl库

c = pycurl.Curl()
c.setopt(c.URL, 'https://curl.haxx.se/dev/')
c.setopt(c.LOCALPORT, 54321)
c.setopt(c.LOCALPORTRANGE, [52314,56321,5532])
c.perform()
c.close()

测试OK,可以直接在curl命令行中测试。

curl --local-port 12520 http://baidu.com

参考

https://stackoverflow.com/questions/47202790/python-requests-how-to-specify-port-for-outgoing-traffic?rq=1

以上这篇Python使用指定端口进行http请求的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中的print()输出

1.普通的输出: print(str)#str是任意一个字符串,数字··· 2.格式化输出: print('1,2,%s,%d'%('asd',4)) 1,2,asd,4 与C语...

python的变量与赋值详细分析

python的变量与赋值详细分析

python的变量与赋值 1.变量的命名规则 变量其实通过一个标记调用内存中的值,而变量名就是这个标记的名称,但是万一这个标记已经被提前占用或者解释器认为这个标记是不合法的,那么就会报...

基于asyncio 异步协程框架实现收集B站直播弹幕

前言 虽然标题是全站,但目前只做了等级 top 100 直播间的全天弹幕收集。 弹幕收集系统基于之前的B 站直播弹幕姬 Python 版修改而来。具体协议分析可以看上一篇文章。 直...

python 调用钉钉机器人的方法

以text格式的消息为例:(只需修改content后的内容) Import json Import requests url='https://oapi.dingtalk.com...

使用coverage统计python web项目代码覆盖率的方法详解

使用coverage统计python web项目代码覆盖率的方法详解

本文实例讲述了使用coverage统计python web项目代码覆盖率的方法。分享给大家供大家参考,具体如下: 在使用python+selenium过程中,有时候考虑代码覆盖率,所以专...