Skip to content

Instantly share code, notes, and snippets.

@scentoni
Last active February 22, 2023 05:26
Show Gist options
  • Save scentoni/12b805dfa3cd2b82ad93370b710f944e to your computer and use it in GitHub Desktop.
Save scentoni/12b805dfa3cd2b82ad93370b710f944e to your computer and use it in GitHub Desktop.
A drop-in replacement for some limited uses of curl, written using only Python3 standard libraries.
#!/usr/bin/env python3
# Makes an HTTP request to the specified URL and sends response to stdout.
# A drop-in replacement for some limited uses of curl, like:
# hcat $URL -H "Authorization: Bearer $TOKEN"
import urllib.parse
import urllib.request
import sys
import argparse
def dictify(kvs, sep):
d = {}
for h in kvs or []:
k, _, v = h.partition(sep)
d[k] = v
return d
parser = argparse.ArgumentParser(description = 'A drop-in replacement for certain uses of curl')
parser.add_argument('path')
parser.add_argument('-X', '--request')
parser.add_argument('-H', '--header', action='append')
parser.add_argument('--data-urlencode', action='append')
args = parser.parse_args()
method = args.request or ('POST' if args.data_urlencode else 'GET')
headers = dictify(args.header, ': ')
parameters = dictify(args.data_urlencode, '=')
data = urllib.parse.urlencode(parameters).encode('ascii') or None
req = urllib.request.Request(args.path, method=method, headers=headers, data=data)
with urllib.request.urlopen(req) as response:
sys.stdout.buffer.write(response.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment