def encode_params(obj, keys=()):
if isinstance(obj, dict):
# key[bar]=1&key[baz]=2
return "&".join(encode_params(val, keys + (key,)) for key, val in obj.items())
# key[foo][]=1&key[foo][]=2
elif isinstance(obj, (list, tuple)):
return "&".join(encode_params(val, keys + ("",)) for val in obj)
# `obj` is just a value, key=1
else:
encoded_keys = ""
for depth, key in enumerate(keys):
# All keys but top-level keys should be in brackets, i.e.
# `key[foo]=1`, not `[key][foo]=1`
encoded_keys += key if depth == 0 else "[" + key + "]"
return quote(encoded_keys) + "=" + quote(obj)
评论列表
文章目录