Creates a `storage` object from dictionary `mapping`, raising `KeyError` if d doesn't have all of the keys in `requireds` and using the default values for keys found in `defaults`. For example, `storify({'a':1, 'c':3}, b=2, c=0)` will return the equivalent of `storage({'a':1, '
(mapping, *requireds, **defaults)
| 115 | |
| 116 | |
| 117 | def storify(mapping, *requireds, **defaults): |
| 118 | """ |
| 119 | Creates a `storage` object from dictionary `mapping`, raising `KeyError` if |
| 120 | d doesn't have all of the keys in `requireds` and using the default |
| 121 | values for keys found in `defaults`. |
| 122 | |
| 123 | For example, `storify({'a':1, 'c':3}, b=2, c=0)` will return the equivalent of |
| 124 | `storage({'a':1, 'b':2, 'c':3})`. |
| 125 | |
| 126 | If a `storify` value is a list (e.g. multiple values in a form submission), |
| 127 | `storify` returns the last element of the list, unless the key appears in |
| 128 | `defaults` as a list. Thus: |
| 129 | |
| 130 | >>> storify({'a':[1, 2]}).a |
| 131 | 2 |
| 132 | >>> storify({'a':[1, 2]}, a=[]).a |
| 133 | [1, 2] |
| 134 | >>> storify({'a':1}, a=[]).a |
| 135 | [1] |
| 136 | >>> storify({}, a=[]).a |
| 137 | [] |
| 138 | |
| 139 | Similarly, if the value has a `value` attribute, `storify will return _its_ |
| 140 | value, unless the key appears in `defaults` as a dictionary. |
| 141 | |
| 142 | >>> storify({'a':storage(value=1)}).a |
| 143 | 1 |
| 144 | >>> storify({'a':storage(value=1)}, a={}).a |
| 145 | <Storage {'value': 1}> |
| 146 | >>> storify({}, a={}).a |
| 147 | {} |
| 148 | |
| 149 | """ |
| 150 | _unicode = defaults.pop("_unicode", False) |
| 151 | |
| 152 | # if _unicode is callable object, use it convert a string to unicode. |
| 153 | to_unicode = safeunicode |
| 154 | if _unicode is not False and hasattr(_unicode, "__call__"): |
| 155 | to_unicode = _unicode |
| 156 | |
| 157 | def unicodify(s): |
| 158 | if _unicode and isinstance(s, str): |
| 159 | return to_unicode(s) |
| 160 | else: |
| 161 | return s |
| 162 | |
| 163 | def getvalue(x): |
| 164 | if hasattr(x, "file") and hasattr(x, "raw"): |
| 165 | return x.file.read() |
| 166 | else: |
| 167 | return unicodify(getattr(x, "value", x)) |
| 168 | |
| 169 | stor = Storage() |
| 170 | for key in requireds + tuple(mapping.keys()): |
| 171 | value = mapping[key] |
| 172 | if isinstance(value, list): |
| 173 | if isinstance(defaults.get(key), list): |
| 174 | value = [getvalue(x) for x in value] |