Spaces:
Runtime error
Runtime error
rodrigomasini
commited on
Commit
•
1cb7677
1
Parent(s):
3be58a1
Create modules/block_requests.py
Browse files- modules/block_requests.py +46 -0
modules/block_requests.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import builtins
|
2 |
+
import io
|
3 |
+
|
4 |
+
import requests
|
5 |
+
|
6 |
+
from modules.logging_colors import logger
|
7 |
+
|
8 |
+
original_open = open
|
9 |
+
original_get = requests.get
|
10 |
+
|
11 |
+
|
12 |
+
class RequestBlocker:
|
13 |
+
|
14 |
+
def __enter__(self):
|
15 |
+
requests.get = my_get
|
16 |
+
|
17 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
18 |
+
requests.get = original_get
|
19 |
+
|
20 |
+
|
21 |
+
class OpenMonkeyPatch:
|
22 |
+
|
23 |
+
def __enter__(self):
|
24 |
+
builtins.open = my_open
|
25 |
+
|
26 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
27 |
+
builtins.open = original_open
|
28 |
+
|
29 |
+
|
30 |
+
def my_get(url, **kwargs):
|
31 |
+
logger.info('Unwanted HTTP request redirected to localhost :)')
|
32 |
+
kwargs.setdefault('allow_redirects', True)
|
33 |
+
return requests.api.request('get', 'http://127.0.0.1/', **kwargs)
|
34 |
+
|
35 |
+
|
36 |
+
def my_open(*args, **kwargs):
|
37 |
+
filename = str(args[0])
|
38 |
+
if filename.endswith('index.html'):
|
39 |
+
with original_open(*args, **kwargs) as f:
|
40 |
+
file_contents = f.read()
|
41 |
+
|
42 |
+
file_contents = file_contents.replace(b'<script src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.3.1/iframeResizer.contentWindow.min.js"></script>', b'')
|
43 |
+
file_contents = file_contents.replace(b'cdnjs.cloudflare.com', b'127.0.0.1')
|
44 |
+
return io.BytesIO(file_contents)
|
45 |
+
else:
|
46 |
+
return original_open(*args, **kwargs)
|