Skip to content

Instantly share code, notes, and snippets.

@stav
Created November 27, 2018 20:11
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 stav/b71d1f643b0a5e25c89991d21cbba74a to your computer and use it in GitHub Desktop.
Save stav/b71d1f643b0a5e25c89991d21cbba74a to your computer and use it in GitHub Desktop.
Querystring prettification
#!/bin/sh
IFS=$'\n' # Allow spaces and other white spaces.
stty -icanon # Disable canonical mode.
stty eof ^D
python3 ~/bin/qs.py
stty icanon # Re-enable canonical mode (assuming it was enabled to begin with).
#!/usr/bin/env python3
import ast
import sys
import pprint
import urllib.parse
input = sys.stdin.readline()
try:
# Convert repr of bytes into bytes
o = ast.literal_eval(input)
if isinstance(o, bytes):
o = o.decode()
else:
o = input.strip()
except (ValueError, SyntaxError):
o = input.strip()
if not isinstance(o, str):
print(f'Input {type(o)} {repr(o)} must be a string')
exit(1)
# o is now a string
print('Input has length', len(o))
if len(o) is 0:
exit(1)
# metal = urllib.parse.unquote(o)
metal = o
# print(f'Metal {type(metal)} has length of:', len(metal))
if '?' in metal:
metal = urllib.parse.urlparse(metal)
query = metal.query
else:
query = metal
print('Query has length', len(query))
parsed = urllib.parse.parse_qs(query, keep_blank_values=True)
parsed = {k: v[0] if len(v) is 1 else v for k, v in parsed.items()}
print(len(parsed.keys()), 'keys')
pprint.pprint(parsed)
@stav
Copy link
Author

stav commented Nov 27, 2018

Prettify a URI's Querystring

$ qs

mailto:ietf-http-wg@w3.org?Subject=Re%3A%20querystring%20part%20of%20cache%20key&In-Reply-To=%3C4A173CA2.7030305%40qbik.com%3E&References=%3C4A173CA2.7030305%40qbik.com%3E&References=%3C4A173CA2.176414%40qbik.com%3E

Input has length 215
Query has length 188
3 keys
{'In-Reply-To': '<4A173CA2.7030305@qbik.com>',
 'References': ['<4A173CA2.7030305@qbik.com>', '<4A173CA2.176414@qbik.com>'],
 'Subject': 'Re: querystring part of cache key'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment