Skip to content

Instantly share code, notes, and snippets.

@weaming
Last active December 22, 2021 16:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaming/811b309229a0d8474166e6c189f3724f to your computer and use it in GitHub Desktop.
Save weaming/811b309229a0d8474166e6c189f3724f to your computer and use it in GitHub Desktop.
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