Software_Programming_python_utils
2020-01-05 12:11:29
Web - URL Parameters
场景: 解析 URL 中的查询字符串, 会遇到指定参数不存在或者空值情况,采用辅助函数
1 def get_first_int(values, key, default=0): 2 found = values.get(key, ['']) 3 if found[0]: 4 found = int(found[0]) 5 else: 6 found = default 7 return found
使用
1 from urllib.parse import parse_qs 2 3 my_values = parse_qs('red=5&blue=0&green=', 4 keep_blank_values=True) 5 6 print(repr(my_values)) 7 8 green = get_first_int(my_values, 'green');
normal - python 深度复制
anotherList = array[:] 或 anotherList = array[-0:]
1 UNDEFINED = object() 2 3 def divide_json(path): 4 handle = open(path,'r+') # May raise IOError 5 try: 6 data = handle.read() # May raise UnicodeDecodeError 7 op = json.loads(data) # May raise ValueError 8 value = ( 9 op['numerator'] 10 op['denominator']) # May raise ZeroDivisionError 11 except ZeroDivisionError as e: 12 return UNDEFINED 13 else: 14 op['result'] = value 15 result = json.dumps(op) 16 handle.seek(0) 17 handle.write(result) # May raise IOError 18 return value 19 finally: 20 handle.close()