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

相关文章

Flask框架实现给视图函数增加装饰器操作示例

本文实例讲述了Flask框架实现给视图函数增加装饰器操作。分享给大家供大家参考,具体如下: 在@app.route的情况下增加装饰器的写法: from flask import Fl...

Python随机生成彩票号码的方法

本文实例讲述了Python随机生成彩票号码的方法。分享给大家供大家参考。具体如下: 前些日子在淘宝上买了一阵子彩票,每次都是使用淘宝的机选,每次一注。后来觉得不如自己写一个机选的程序有意...

python 文件操作api(文件操作函数)

python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下...

Python openpyxl读取单元格字体颜色过程解析

问题 我试图打印some_cell.font.color.rgb并得到各种结果。 对于一些人,我得到了我想要的东西(比如“ FF000000”),但对于其他人,它给了我Value mus...

详解Python的Django框架中的模版相关知识

HTML被直接硬编码在 Python 代码之中。 def current_datetime(request): now = datetime.datetime.now() h...