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

yipeiwu_com6年前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设计】。

相关文章

Django实现一对多表模型的跨表查询方法

当有两个表,例如一个学生表,一个班级表,是多对一的关系。 方法1: c = models.Class.object.get(pk=1) #查询到ID为1的班级 stus = mode...

在Python的Django框架上部署ORM库的教程

Python ORM 概览 作为一个美妙的语言,Python 除了 SQLAlchemy 外还有很多ORM库。在这篇文章里,我们将来看看几个流行的可选ORM 库,以此更好地窥探到Pyth...

matlab中实现矩阵删除一行或一列的方法

实例如下所示: >> A=[1,2,3;4,5,6;7,8,9] A = 1 2 3 4 5 6 7 8 9 删除行: >> A...

Python实现手机号自动判断男女性别(实例解析)

Python实现手机号自动判断男女性别(实例解析)

本文性别判断主要依靠airtest中的自动化测试实现 通过自动对比支付宝页面男女图像,从而实现男女判断 代码如下: 男女判断函数: // An highlighted block...

Python单元测试框架unittest使用方法讲解

概述 1.测试脚手架(test fixture) 测试准备前要做的工作和测试执行完后要做的工作.包括setUp()和tearDown(). 2.测试案例(test case) 最小的测试...