需求:有时候需要将GET参数转为字典再动态增加参数 注意:此代码来源Tornado源码
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib.parse from typing import Dict, List def parse_qs_bytes( qs: str, keep_blank_values: bool = False, strict_parsing: bool = False, code_type: str = "utf-8" ) -> Dict[str, List[bytes]]: """将查询的字符串转为字典类型,并且value转为字节类型""" result = urllib.parse.parse_qs( qs, keep_blank_values, strict_parsing, encoding="latin1", errors="strict" ) encoded = {} for k, v in result.items(): encoded[k] = [i.encode(code_type) for i in v] return encoded if __name__ == '__main__': ret = parse_qs_bytes("username=test&password=admin&content=中国人") print(ret) ret['type'] = 0 print(urllib.parse.urlencode(ret))
运行结果
{'username': [b'test'], 'password': [b'admin'], 'content': [b'\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba']} username=%5Bb%27test%27%5D&password=%5Bb%27admin%27%5D&content=%5Bb%27%5Cxe4%5Cxb8%5Cxad%5Cxe5%5Cx9b%5Cxbd%5Cxe4%5Cxba%5Cxba%27%5D&type=0