-
-
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.
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
#!/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