-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetch.py
36 lines (31 loc) · 1.1 KB
/
fetch.py
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
import hashlib
import importlib.util
import sys
from pathlib import Path
from types import ModuleType
from urllib.parse import urlparse
import requests
def fetch(path, name=None):
"""Load a module from an arbitrary path."""
path = Path(path)
if name is None:
name = path.stem
spec = importlib.util.spec_from_file_location(name, str(path))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def import_from_url(url, checksum, name=None, algorithm='sha256'):
"""lol dont do this"""
code = requests.get(url).text
if checksum != hashlib.new(algorithm, code).hexdigest():
raise ValueError('checksum mismatch for {}'.format(url))
if name is None:
name = Path(urlparse(url).path).stem
sys.modules[name] = module = ModuleType(name)
module.__loader__ = None
# Non-package modules should not have a __path__ attribute.
# When the module is not a package, __package__ should be set to the
# empty string for top-level modules
module.__package__ = ''
exec(code, module.__dict__)
return module