def get_typed_dictionary_from_request_dict(GET, skip_empty_lists=True, suppress_convert_exception=True): """ Request GET variables to typed dictionary. types: __int -> int() or None __str -> unicode() or None __bool -> bool() or None __float -> float() or None __type__list -> [type() if not suppress_convert_exception else None, ..] other -> skip ex: url?qwe__int__list=2&qwe__int__list=4 => {u'qwe': [2, 4]} url?qwe__int__list=2&qwe__str__list=4 => {u'qwe': [u'4', 2]} url?qwe__bool=2 => {u'qwe': True} url?qwe__bool=t => {u'qwe': True} url?qwe__bool=0 => {u'qwe': False} url?qwe__bool=f => {u'qwe': False} url?qwe__float=2.3 => {u'qwe': 2.3} """ def to_bool(str): if str.isdigit(): return bool(int(str)) elif str.lower() in ['true', 't']: return True elif str.lower() in ['false', 'f']: return False return len(str) > 0 rez = dict() for key in GET.keys(): real_key = key is_list = key.endswith('__list') if is_list: key = key[:-6] __type = None if key.endswith('__int'): key = key[:-5] __type = int elif key.endswith('__str'): key = key[:-5] __type = unicode elif key.endswith('__bool'): key = key[:-6] __type = to_bool elif key.endswith('__float'): key = key[:-7] __type = float if __type and len(key): value = None if is_list: getlist = GET.getlist(real_key) value = [] for x in getlist: typed = None try: typed = __type(x) except ValueError as e: if not suppress_convert_exception: raise e value.append(typed) if len(value) == 0 and skip_empty_lists: continue else: try: value = __type(GET.get(real_key)) except ValueError as e: if not suppress_convert_exception: raise e if is_list and key in rez: rez[key].extend(value) else: rez[key] = value return rez