This repository was archived by the owner on Mar 10, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrequests.py
More file actions
74 lines (57 loc) · 2.4 KB
/
requests.py
File metadata and controls
74 lines (57 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from urllib import request
import json
_ORIGINAL_SOCKET = None
def socks_monkey_patch(proxy_info: dict = None):
import socks
import socket
if proxy_info["username"] and proxy_info["password"]:
socks.set_default_proxy(
socks.SOCKS5 if proxy_info["type"] == "SOCKS5" else socks.SOCKS4,
proxy_info["host"],
proxy_info["port"],
username=proxy_info["username"],
password=proxy_info["password"]
)
else:
socks.set_default_proxy(
socks.SOCKS5 if proxy_info["type"] == "SOCKS5" else socks.SOCKS4,
proxy_info["host"],
proxy_info["port"],
)
_ORIGINAL_SOCKET = socket.socket # save our socket before patching monkey patching socks
socket.socket = socks.socksocket
def http_monkey_patch(proxy_info: dict = None):
if proxy_info and proxy_info["type"] == "HTTP":
proxy_str = f"{proxy_info['host']}:{proxy_info['port']}"
if proxy_info["username"] and proxy_info["password"]:
proxy_str = f"{proxy_info['username']}:{proxy_info['password']}@{proxy_str}"
proxy_handler = request.ProxyHandler({
'http': 'http://' + proxy_str,
'https': 'http://' + proxy_str
})
opener = request.build_opener(proxy_handler)
request.install_opener(opener)
def undo_monkey_patching():
# This undos the custom opener for urllib
request.install_opener(request.build_opener())
# This tries to undo the monkey patching we did using Pysocks
if _ORIGINAL_SOCKET:
import socket
socket.socket = _ORIGINAL_SOCKET
def http_request(url: str, method: str, auth_token: str = None, payload: dict = None, longpoll: int = -1) -> dict:
if payload:
payload = json.dumps(payload).encode()
if payload:
req = request.Request(url, data=payload, method=method.upper())
req.add_header("Content-Type", "application/json")
else:
req = request.Request(url, method=method.upper())
if auth_token:
req.add_header("Authorization", "Bearer " + auth_token)
# NOTE: urllib raises a HTTPError for status code >= 400
if longpoll == -1:
with request.urlopen(req) as response:
return json.loads(response.read().decode())
else:
with request.urlopen(req, timeout=longpoll) as response:
return json.loads(response.read().decode())