def _env_convert(self, value): """ Converts the following type tags when parsing environment variables: * ``!!bool`` * ``!!float`` * ``!!int`` * ``!!str`` * ``!!timestamp`` The tag ``!!timestamp`` uses :mod:`python-dateutil` to parse date/time strings. :param value: to parse :return: parsed value if any of the listed tags applies, else the original value is returned """ if value is None: return None converter = { "!!bool": lambda r: parse_boolean(r), "!!float": lambda r: float(r), "!!int": lambda r: int(r), "!!str": lambda r: str(r), "!!timestamp": lambda r: dateutil.parser.parse(r) , } for typ, conv in converter.items(): if value.startswith(typ + " "): upd = value[len(typ) + 1:] return conv(upd) return value
def get_argument(self, name, as_type=None, remove=False, dict_decode=None, *args, **kwargs): """ Returns the value of the argument with the given name. If default is not provided, the argument is considered to be required, and we raise a `MissingArgumentError` if it is missing. If the argument appears in the url more than once, we return the last value. If ``as_type`` is provided, then the variable type is converted. The method supports the following variable types: * int * float * bool - using :meth:`parse_boolean <core4.util.data.parse_boolean>` * str * dict - using :mod:`json.loads` * list - using :mod:`json.loads` * datetime - using :meth:`dateutil.parser.parse` :param name: variable name :param default: value :param as_type: Python variable type :param remove: remove parameter from request arguments, defaults to ``False`` :param dict_decode: custom function for dict decoding :return: value """ kwargs["default"] = kwargs.get("default", ARG_DEFAULT) ret = self._get_argument(name, source=self.request.arguments, *args, strip=False, **kwargs) if as_type and ret is not None: try: if as_type == bool: if isinstance(ret, bool): return ret return parse_boolean(ret, error=True) if as_type == dict: if isinstance(ret, dict): return ret return json_decode(ret, object_hook=dict_decode) if as_type == list: if isinstance(ret, list): return ret return json_decode(ret) if as_type == datetime.datetime: if isinstance(ret, datetime.datetime): dt = ret else: dt = dateutil.parser.parse(ret) if dt.tzinfo is None: return dt utc_struct_time = time.gmtime(time.mktime(dt.timetuple())) return datetime.datetime.fromtimestamp( time.mktime(utc_struct_time)) if as_type == ObjectId: if isinstance(ret, ObjectId): return ret return ObjectId(ret) return as_type(ret) except: raise core4.error.ArgumentParsingError( "parameter [%s] expected as_type [%s]", name, as_type.__name__) from None if remove and name in self.request.arguments: del self.request.arguments[name] return ret