Skip to content

Instantly share code, notes, and snippets.

@amberj
Last active October 22, 2023 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amberj/b732c41612d901013b99a54d8a3f9adb to your computer and use it in GitHub Desktop.
Save amberj/b732c41612d901013b99a54d8a3f9adb to your computer and use it in GitHub Desktop.
Convert curl to requests using uncurl
#!/usr/bin/env python3
import time
import uncurl
'''
This script uses: https://github.com/spulec/uncurl
To install: Setup virtualenv, then run:
pip install uncurl requests
'''
#####################################################################
############################## INPUT ################################
#####################################################################
curl_command = '''
curl 'https://api.ipify.org?format=json'
'''
#####################################################################
############################## Conversion ###########################
#####################################################################
def curl_to_requests(curl_command):
uncurled_requests = uncurl.parse(curl_command)
#print(uncurled_requests)
#time.sleep(100)
with open('readonly_converted_request_from_curl.py', "w+") as f:
f.write("import requests\n\ndef readonly_converted_request():\n res = ")
with open('readonly_converted_request_from_curl.py', "a+") as f:
f.write(uncurled_requests)
with open('readonly_converted_request_from_curl.py', "a+") as f:
f.write("\n #print(res.text)\n return res\n")
#####################################################################
############################## Convert ##############################
#####################################################################
print("\nConverting curl command to Python requests equivalent")
curl_to_requests(curl_command)
print("Waiting for 2 seconds...")
time.sleep(2)
import readonly_converted_request_from_curl as converted
print(converted.readonly_converted_request())
#####################################################################
############################## Extract Headers ######################
#####################################################################
def extract_header_cookies_from_curl(curl_command):
uncurled_req = uncurl.parse_context(curl_command)
uncurled_header = uncurled_req.headers
uncurled_cookies = uncurled_req.cookies
return uncurled_header, uncurled_cookies
uncurled_header, uncurled_cookies = extract_header_cookies_from_curl(curl_command)
print(uncurled_header, uncurled_cookies)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment