Last active
December 22, 2021 16:36
-
-
Save weaming/811b309229a0d8474166e6c189f3724f to your computer and use it in GitHub Desktop.
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 json | |
from functools import wraps | |
import requests | |
allow_methods = [ | |
'options', | |
'head', | |
'get', | |
'post', | |
'put', | |
'delete', | |
] | |
def patch_requests_method(method: str): | |
assert method in allow_methods, f'method must be in {allow_methods}' | |
fn_method = getattr(requests, method) | |
@wraps(fn_method) | |
def new_fn(*args, **kw): | |
request = {'method': method, 'arguments': {'args': args, 'kwargs': kw}} | |
res = fn_method(*args, **kw) | |
try: | |
js = res.json() | |
except json.decoder.JSONDecodeError: | |
js = None | |
response = { | |
'status_code': res.status_code, | |
'headers': dict(res.headers), | |
'cookies': dict(res.cookies), | |
} | |
if js is None: | |
response['text'] = res.text | |
else: | |
response['json'] = js | |
print( | |
json.dumps( | |
{'request': request, 'response': response}, indent=2, ensure_ascii=False | |
) | |
) | |
return res | |
setattr(requests, '_' + method, fn_method) | |
setattr(requests, method, new_fn) | |
return new_fn | |
def patch_requests_all(): | |
for x in allow_methods: | |
print(f'patched requests.{x}') | |
patch_requests_method(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment