Overriding stdlib http package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from importlib import invalidate_caches | |
from importlib.abc import MetaPathFinder | |
from importlib.machinery import ModuleSpec, SourceFileLoader | |
from os.path import dirname, join, abspath, isdir, isfile | |
class Finder(MetaPathFinder): | |
def find_spec(self, fullname, path, target=None): | |
name_parts = fullname.split('.') | |
if name_parts[0] != 'http': | |
# don't worry about non-http modules | |
return | |
name_parts[0] = 'httplib3' | |
find_path = abspath(join(*name_parts)) | |
if isdir(find_path): | |
origin = join(find_path, '__init__.py') | |
else: | |
origin = '{}.py'.format(find_path) | |
if not isfile(origin): | |
# assume it's a module attribute | |
return | |
loader = SourceFileLoader(fullname, origin) | |
is_package = loader.is_package(fullname) | |
spec = ModuleSpec( | |
fullname, loader, is_package=is_package, origin=origin) | |
if is_package: | |
spec.submodule_search_locations = [dirname(__file__)] | |
return spec | |
def inject(): | |
invalidate_caches() | |
for k in [k for k in sys.modules.keys() if k.startswith('http')]: | |
del sys.modules[k] | |
sys.meta_path.insert(0, Finder()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you really want to delete all already-loaded modules that start with 'http'? How about just a whitelist of names and prefixes (if necessary)? If someone tries to use their "httputils" module they might be surprised. There are 58 distributions on pypi that start with "http":