Created
July 13, 2016 15:12
-
-
Save ficapy/e3cba14a71a5d6bba8919c9b6e4df88f to your computer and use it in GitHub Desktop.
代替/etc/hosts 当requests.get的时候使用指定的ip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# Author: Ficapy | |
# Create: '7/12/16' | |
import socket | |
import requests | |
def getitem(pos, seq): | |
tmp = seq | |
for i in pos: | |
tmp = tmp.__getitem__(int(i)) | |
return tmp | |
def modify_tuple(seq, pos, value): | |
if isinstance(seq, tuple): | |
seq = list(seq) | |
seq.append(True) | |
else: | |
seq.append(False) | |
for index, i in enumerate(pos): | |
command = ''.join(['[{}]'.format(x) for x in pos[:index + 1]]) | |
if index + 1 == len(pos): | |
exec (''.join(['seq', command]) + '=' + 'value') | |
break | |
val = getitem(pos[:index + 1], seq) | |
if isinstance(val, tuple): | |
val = list(val) | |
val.append(True) | |
else: | |
val.append(False) | |
exec (''.join(['seq', command]) + '=' + 'val') | |
for index, i in enumerate(pos[:-1]): | |
command = ''.join(['[{}]'.format(x) for x in pos[:-index - 1]]) | |
val = getitem(pos[:-index - 1], seq) | |
if val[-1]: | |
val = tuple(val[:-1]) | |
else: | |
val = val[:-1] | |
exec (''.join(['seq', command]) + '=' + 'val') | |
if seq[-1]: | |
seq = tuple(seq[:-1]) | |
else: | |
seq = seq[:-1] | |
return seq | |
def hosts(func): | |
def inner(*args): | |
ret = func(*args) | |
if 'live' in args[0]: | |
ret = ret[0] | |
ret = modify_tuple(ret, '40', '204.79.197.213') | |
return [ret] | |
return ret | |
return inner | |
socket.getaddrinfo = hosts(socket.getaddrinfo) | |
requests.get(URL) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment