Python Requests, how to bind to different source ip for each request? [duplicate]

假装没事ソ 提交于 2019-11-30 09:58:02
Ian Stapleton Cordasco

For each request, there is no elegant solution, but you'll need to use a requests Session object and mount a new transport adapter for each request.

You can find example code for the transport adapter in this issue comment, or you can use the adapter included in the requests-toolbelt package, like so

import requests
from requests_toolbelt.adapters import source

responses = []
s = requests.Session()
for source_ip, url in list_of_sources_and_urls:
    new_source = source.SourceAddressAdapter(source_ip)
    s.mount('http://', new_source)
    s.mount('https://', new_source)
    responses.append(s.get(url))

That assumes that list_of_sources_and_urls looks like

 [('127.0.0.1', 'https://google.com'),
  ('255.255.254.0', 'https://yahoo.com'),
  # ...
  ]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!