Python请求,如何为每个请求绑定到不同的源IP? [英] Python Requests, how to bind to different source ip for each request?

查看:367
本文介绍了Python请求,如何为每个请求绑定到不同的源IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习一些python,而我要测试的逻辑也有问题. 目前,我的代码以这样的方式编写:在进程启动时,与source_address的绑定不会改变

I'm trying to learn some python, and i'm having issues with the logic in what I want to test. Currently my code is written in a way that binding to source_address doesn't change when the process starts

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

推荐答案

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

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.

您可以在此问题注释中找到传输适配器的示例代码,或者您可以使用requests-toolbelt包中包含的适配器,就像这样

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

假定list_of_sources_and_urls看起来像

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

这篇关于Python请求,如何为每个请求绑定到不同的源IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆