Last active
November 23, 2022 14:58
-
-
Save asfaltboy/8df5cc73c63d897ba6344e41ee2e10b5 to your computer and use it in GitHub Desktop.
Django HTTP Request to curl command (for replay)
This file contains hidden or 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
""" | |
Convert a Django HTTPRequest object (or dictionary of such a request) into a | |
cURL command. | |
""" | |
import json | |
import sys | |
required_fields = ['META', 'META.REQUEST_METHOD', 'META.SERVER_NAME', 'META.PATH_INFO'] | |
def convert(word, delim='-'): | |
return delim.join(x.capitalize() or '_' for x in word.split('_')) | |
def get_request_dict(request): | |
if isinstance(request, basestring): | |
try: | |
return json.loads(request) | |
except Exception: | |
print('Must be given a valid JSON') | |
raise | |
if not isinstance(request, dict): | |
return vars(request) | |
return request | |
def get_headers(request): | |
headers = {convert(name[5:]): value for name, value in | |
request['META'].items() if name.startswith('HTTP_')} | |
return headers | |
def validate_request(request, required_attributes=required_fields, prefix=''): | |
for field in required_attributes: | |
if '.' in field: | |
parts = field.split('.') | |
validate_request(request[parts[0]], | |
required_attributes=['.'.join(parts[1:])], | |
prefix='%s.' % parts[0]) | |
continue | |
assert field in request, ( | |
'The `request.%s%s` attribute is required' % (prefix, field)) | |
def get_curl(request): | |
request = get_request_dict(request) | |
validate_request(request) | |
assert request['META']['REQUEST_METHOD'] == 'GET', 'Only GET currently supported' | |
headers = get_headers(request) | |
url = '{server}{path}?{query}'.format( | |
server=request['META']['SERVER_NAME'], | |
path=request['META']['PATH_INFO'], | |
query=request['META']['QUERY_STRING'], | |
) | |
return 'curl {headers} "{url}"'.format( | |
headers=' '.join(('-H "%s: %s"' % (h, v)) for h, v in headers.items()), | |
url=url) | |
if __name__ == '__main__': | |
assert len(sys.argv) == 2, "Accepts exactly 1 param" | |
try: | |
unescaped = sys.argv[1].decode('unicode_escape') | |
request = json.loads(unescaped) | |
except Exception: | |
print('Must be given a valid JSON') | |
raise | |
curl_body = get_curl(request) | |
print('\nUse the follow curl command to "replay" the request:\n{}'.format(curl_body)) |
You should document it
I completely forgot I even ever wrote this 😅 ... send over some docstrings and I'll add them here, or fork it if you like
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should document it