Skip to content

Instantly share code, notes, and snippets.

@yuanxu
Created August 22, 2013 08:31
Show Gist options
  • Save yuanxu/6304581 to your computer and use it in GitHub Desktop.
Save yuanxu/6304581 to your computer and use it in GitHub Desktop.
设置socket,支持代理服务器
# coding=utf-8
from django.conf import LazySettings
def _setup_proxy():
'''
初始化proxy
@return:
'''
settings = LazySettings()
proxy = settings.PROXY_SERVER
if proxy:
import socks
import socket
def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
msg = "getaddrinfo returns an empty list"
host, port = address
if len(address) == 2 and isinstance(address, (list, tuple)) and isinstance(address[0], unicode):
address = (str(address[0]), address[1])
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socks.socksocket(af, socktype, proto)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
sock.connect(address)
return sock
except socket.error, msg:
if sock is not None:
sock.close()
raise socket.error, msg
socket.create_connection = _create_connection
# Magic!
def getaddrinfo(*args):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
socket.getaddrinfo = getaddrinfo
def set_proxy():
'''
启用proxy
@return:
'''
settings = LazySettings()
proxy = settings.PROXY_SERVER
if proxy:
import socks
proxy_type, proxy_ip, proxy_port = proxy
socks.setdefaultproxy(proxy_type, proxy_ip, proxy_port)
def unset_proxy():
'''
停用proxy
@return:
'''
settings = LazySettings()
proxy = settings.PROXY_SERVER
if proxy:
from socks import setdefaultproxy
setdefaultproxy()
_setup_proxy()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment