Python请求,如何为每个请求绑定到不同的源IP?

时间:2015-02-27 19:42:20

标签: python sockets python-requests python-sockets

我正在尝试学习一些python,我在测试中遇到了逻辑问题。 目前,我的代码是以一种方式编写的,即当进程启动时,对source_address的绑定不会改变

import socket
import requests

real_create_conn = socket.create_connection

def set_src_addr(*args):
    address, timeout = args[0], args[1]
    source_address = ('201.X.X.1', 0)
    return real_create_conn(address, timeout, source_address)

socket.create_connection = set_src_addr

r = requests.get('http://www.mywebpage.com/main')
print r.status_code 
if r.status_code == 404
   print "Webpage Down!"

r = requests.get('http://www.mywebpage.com/blog')
print r.status_code 
if r.status_code == 204
   print "Error occured!"

我正在寻找这样的事情

import socket
import requests


While 1: 

      #bind to source address 201.X.X.1
      #Send request to main webpage
      #print result
      time.sleep(300) # 5 minutes

      #bind to source address 201.X.X.12
      #Send request to blog webpage
      #print result
      time.sleep(300) # 5 minutes

1 个答案:

答案 0 :(得分:14)

对于每个请求,没有优雅的解决方案,但您需要使用请求Session对象并为每个请求安装新的传输适配器。

您可以在this issue comment中找到传输适配器的示例代码,或者您可以使用requests-toolbelt包中包含的适配器,如此

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))

假设list_of_sources_and_urls看起来像

 [('127.0.0.1', 'https://google.com'),
  ('255.255.254.0', 'https://yahoo.com'),
  # ...
  ]