Skip to content

Instantly share code, notes, and snippets.

@Beastrock
Last active September 15, 2017 14:00
Show Gist options
  • Save Beastrock/ddb344acab0dbaa0bb706333aee76125 to your computer and use it in GitHub Desktop.
Save Beastrock/ddb344acab0dbaa0bb706333aee76125 to your computer and use it in GitHub Desktop.
Using socks proxy with requests.
# requirements.txt
# PySocks==1.6.7
# requests==2.18.0 (!)
import socket
import socks
import requests
DEFAULT_SOCKET = socket.socket # Remove this if you don't plan to "deactivate" the proxy later
ip = 'xx.xxx.xxx.xx' # change your proxy's ip
port = 9999 # change your proxy's port (int)
# Set up a proxy
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, port)
socket.socket = socks.socksocket
s = requests.Session()
s.get(.....)
# Use this only if you plan to make requests without any proxies later
socket.socket = DEFAULT_SOCKET
# OR use contect manager
from contextlib import contextmanager
DEFAULT_SOCKET = socket.socket
@contextmanager
def sock_socket(ip, port):
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, port)
socket.socket = socks.socksocket
yield
socket.socket = DEFAULT_SOCKET
# example
with sock_socket(ip,port):
requests.get....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment