Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Last active September 24, 2018 18:38
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 SpotlightKid/88bdd7310e0a8f0c91d69a532b86cbeb to your computer and use it in GitHub Desktop.
Save SpotlightKid/88bdd7310e0a8f0c91d69a532b86cbeb to your computer and use it in GitHub Desktop.
Reduced urllib.parse_qsl implementation for MicroPython
# -*- coding: utf-8 -*-
def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
encoding='utf-8', errors='replace'):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed. May be a unicode
string or a UTF-8 encoded byte-string.
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings. A
true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
strict_parsing: flag indicating what to do with parsing errors. If
false (the default), errors are silently ignored. If true,
errors raise a ValueError exception.
encoding: specify how to decode percent-encoded sequences into Unicode
characters.
Returns a list of (name, value) tuples.
"""
if isinstance(qs, bytes):
qs = qs.decode('utf-8')
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
r = []
for name_value in pairs:
if not name_value and not strict_parsing:
continue
nv = name_value.split('=', 1)
if len(nv) != 2:
if strict_parsing:
raise ValueError("bad query field: %r" % (name_value,))
# Handle case of a control-name with no equal sign
if keep_blank_values:
nv.append('')
else:
continue
if len(nv[1]) or keep_blank_values:
name = nv[0].replace('+', ' ')
name = unquote(name, encoding)
value = nv[1].replace('+', ' ')
value = unquote(value, encoding)
r.append((name, value))
return r
def unquote(string, encoding='utf-8'):
"""unquote('abc%20def') -> 'abc def'.
string may also be an UTF-8 encoded byte-string.
"""
if not string:
return ''
if isinstance(string, str):
string = string.encode('utf-8')
bits = string.split(b'%')
if len(bits) == 1:
return string.decode(encoding)
res = [bits[0]]
append = res.append
for item in bits[1:]:
try:
append(bytes([int(item[:2], 16)]))
append(item[2:])
except KeyError:
append(b'%')
append(item)
return b''.join(res).decode(encoding)
if __name__ == '__main__':
#from urlparse import parse_qsl
url = 'power=10&time=0.7&long+name+with+spaces=value%20with%20%C3%BCnicode'
for name, val in parse_qsl(url):
print("%s: %s" % (name, val))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment