Created
September 21, 2015 21:49
-
-
Save saxbophone/45236286b93f0a5f94c6 to your computer and use it in GitHub Desktop.
An experiment into monkey-patching the rather excellent Requests library
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 __main__ | |
import types | |
# patch_requests by Joshua Saxby | |
# An experiment into monkey-patching the rather excellent Requests | |
# library so the module can be hooked on a global level with minimal | |
# code having to be written by the end-user. | |
try: | |
# Try block is for when the module has already been loaded | |
assert isinstance(__main__.requests, types.ModuleType) | |
except AttributeError: | |
# Except is for when we need to import it ourselves | |
import requests | |
__main__.requests = requests | |
assert isinstance(__main__.requests, types.ModuleType) | |
finally: | |
# Now, monkey-patch that module! ;) | |
backup_request = __main__.requests.api.request | |
def replacement_request(*args, **kwargs): | |
print('request function called') | |
return backup_request(*args, **kwargs) | |
__main__.requests.api.request = replacement_request |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment