set Set the value into the configuration table for this current user (or the given user_id, when called outside a request context). :param value: Value to be set :param user_id: User to set the preference for; defaults to the current
(self, value, user_id=None)
| 166 | return False, None |
| 167 | |
| 168 | def set(self, value, user_id=None): |
| 169 | """ |
| 170 | set |
| 171 | Set the value into the configuration table for this current user |
| 172 | (or the given user_id, when called outside a request context). |
| 173 | |
| 174 | :param value: Value to be set |
| 175 | :param user_id: User to set the preference for; defaults to the |
| 176 | current user. |
| 177 | |
| 178 | :returns: nothing. |
| 179 | """ |
| 180 | # We can't store the values in the given format, we need to convert |
| 181 | # them in string first. We also need to validate the value type. |
| 182 | |
| 183 | parser_map = { |
| 184 | 'integer': int, |
| 185 | 'numeric': float, |
| 186 | 'date': dateutil_parser.parse, |
| 187 | 'datetime': dateutil_parser.parse, |
| 188 | 'keyboardshortcut': json.dumps |
| 189 | } |
| 190 | |
| 191 | error_map = { |
| 192 | 'keyboardshortcut': 'keyboard shortcut' |
| 193 | } |
| 194 | |
| 195 | try: |
| 196 | if self._type in ('boolean', 'switch', 'node'): |
| 197 | assert isinstance(value, bool) |
| 198 | elif self._type == 'options': |
| 199 | has_value = next((True for opt in self.options |
| 200 | if 'value' in opt and opt['value'] == value), |
| 201 | False) |
| 202 | assert (has_value or (self.control_props and |
| 203 | (self.control_props.get('tags') or |
| 204 | self.control_props.get('creatable')))) |
| 205 | elif self._type == 'date': |
| 206 | value = parser_map[self._type](value).date() |
| 207 | else: |
| 208 | value = parser_map.get(self._type, lambda v: v)(value) |
| 209 | if self._type == 'integer': |
| 210 | value = self.normalize_range(value) |
| 211 | assert isinstance(value, int) |
| 212 | if self._type == 'numeric': |
| 213 | value = self.normalize_range(value) |
| 214 | assert ( |
| 215 | isinstance(value, int) or isinstance(value, float) or |
| 216 | isinstance(value, decimal.Decimal)) |
| 217 | except Exception as e: |
| 218 | current_app.logger.exception(e) |
| 219 | return False, gettext( |
| 220 | "Invalid value for {0} option.".format( |
| 221 | error_map.get(self._type, self._type))) |
| 222 | |
| 223 | uid = user_id if user_id is not None else current_user.id |
| 224 | pref = UserPrefTable.query.filter_by( |
| 225 | pid=self.pid |