##// END OF EJS Templates
hgweb: refactor multirequest to be a dict of lists...
Gregory Szorc -
r37012:44467a4d default
parent child Browse files
Show More
@@ -28,39 +28,22 b' class multidict(object):'
28 28 This is inspired by WebOb's class of the same name.
29 29 """
30 30 def __init__(self):
31 # Stores (key, value) 2-tuples. This isn't the most efficient. But we
32 # don't rely on parameters that much, so it shouldn't be a perf issue.
33 # we can always add dict for fast lookups.
34 self._items = []
31 self._items = {}
35 32
36 33 def __getitem__(self, key):
37 34 """Returns the last set value for a key."""
38 for k, v in reversed(self._items):
39 if k == key:
40 return v
41
42 raise KeyError(key)
35 return self._items[key][-1]
43 36
44 37 def __setitem__(self, key, value):
45 38 """Replace a values for a key with a new value."""
46 try:
47 del self[key]
48 except KeyError:
49 pass
50
51 self._items.append((key, value))
39 self._items[key] = [value]
52 40
53 41 def __delitem__(self, key):
54 42 """Delete all values for a key."""
55 oldlen = len(self._items)
56
57 self._items[:] = [(k, v) for k, v in self._items if k != key]
58
59 if oldlen == len(self._items):
60 raise KeyError(key)
43 del self._items[key]
61 44
62 45 def __contains__(self, key):
63 return any(k == key for k, v in self._items)
46 return key in self._items
64 47
65 48 def __len__(self):
66 49 return len(self._items)
@@ -73,21 +56,18 b' class multidict(object):'
73 56
74 57 def add(self, key, value):
75 58 """Add a new value for a key. Does not replace existing values."""
76 self._items.append((key, value))
59 self._items.setdefault(key, []).append(value)
77 60
78 61 def getall(self, key):
79 62 """Obtains all values for a key."""
80 return [v for k, v in self._items if k == key]
63 return self._items.get(key, [])
81 64
82 65 def getone(self, key):
83 66 """Obtain a single value for a key.
84 67
85 68 Raises KeyError if key not defined or it has multiple values set.
86 69 """
87 vals = self.getall(key)
88
89 if not vals:
90 raise KeyError(key)
70 vals = self._items[key]
91 71
92 72 if len(vals) > 1:
93 73 raise KeyError('multiple values for %r' % key)
@@ -95,14 +75,7 b' class multidict(object):'
95 75 return vals[0]
96 76
97 77 def asdictoflists(self):
98 d = {}
99 for k, v in self._items:
100 if k in d:
101 d[k].append(v)
102 else:
103 d[k] = [v]
104
105 return d
78 return {k: list(v) for k, v in self._items.iteritems()}
106 79
107 80 @attr.s(frozen=True)
108 81 class parsedrequest(object):
General Comments 0
You need to be logged in to leave comments. Login now