Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/rest_framework/utils/html.py: 61%

30 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1""" 

2Helpers for dealing with HTML input. 

3""" 

4import re 

5 

6from django.utils.datastructures import MultiValueDict 

7 

8 

9def is_html_input(dictionary): 

10 # MultiDict type datastructures are used to represent HTML form input, 

11 # which may have more than one value for each key. 

12 return hasattr(dictionary, 'getlist') 

13 

14 

15def parse_html_list(dictionary, prefix='', default=None): 

16 """ 

17 Used to support list values in HTML forms. 

18 Supports lists of primitives and/or dictionaries. 

19 

20 * List of primitives. 

21 

22 { 

23 '[0]': 'abc', 

24 '[1]': 'def', 

25 '[2]': 'hij' 

26 } 

27 --> 

28 [ 

29 'abc', 

30 'def', 

31 'hij' 

32 ] 

33 

34 * List of dictionaries. 

35 

36 { 

37 '[0]foo': 'abc', 

38 '[0]bar': 'def', 

39 '[1]foo': 'hij', 

40 '[1]bar': 'klm', 

41 } 

42 --> 

43 [ 

44 {'foo': 'abc', 'bar': 'def'}, 

45 {'foo': 'hij', 'bar': 'klm'} 

46 ] 

47 

48 :returns a list of objects, or the value specified in ``default`` if the list is empty 

49 """ 

50 ret = {} 

51 regex = re.compile(r'^%s\[([0-9]+)\](.*)$' % re.escape(prefix)) 

52 for field, value in dictionary.items(): 

53 match = regex.match(field) 

54 if not match: 54 ↛ 56line 54 didn't jump to line 56, because the condition on line 54 was never false

55 continue 

56 index, key = match.groups() 

57 index = int(index) 

58 if not key: 

59 ret[index] = value 

60 elif isinstance(ret.get(index), dict): 

61 ret[index][key] = value 

62 else: 

63 ret[index] = MultiValueDict({key: [value]}) 

64 

65 # return the items of the ``ret`` dict, sorted by key, or ``default`` if the dict is empty 

66 return [ret[item] for item in sorted(ret)] if ret else default 66 ↛ exitline 66 didn't run the list comprehension on line 66

67 

68 

69def parse_html_dict(dictionary, prefix=''): 

70 """ 

71 Used to support dictionary values in HTML forms. 

72 

73 { 

74 'profile.username': 'example', 

75 'profile.email': 'example@example.com', 

76 } 

77 --> 

78 { 

79 'profile': { 

80 'username': 'example', 

81 'email': 'example@example.com' 

82 } 

83 } 

84 """ 

85 ret = MultiValueDict() 

86 regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix)) 

87 for field in dictionary: 

88 match = regex.match(field) 

89 if not match: 89 ↛ 91line 89 didn't jump to line 91, because the condition on line 89 was never false

90 continue 

91 key = match.groups()[0] 

92 value = dictionary.getlist(field) 

93 ret.setlist(key, value) 

94 

95 return ret