def on_message(self, message): """ Processes client messages of ``type`` * _message_ * _interest_ All other or undefined message types are ignored. :param message: str representing valid json """ try: request = json_decode(message) except: ret = "error parsing json data" else: cmd = request.get("type", "unknown") meth = getattr(self, "proc_" + cmd, self.proc_unknown) ret = meth(request) self.write_message(ret)
async def prepare(self): """ Prepares the handler with * setting the ``request_id`` * preparing the combined parsing of query and body arguments * authenticates and authorizes the user Raises 401 error if authentication and authorization fails. """ if self.request.body: try: body_arguments = json_decode(self.request.body.decode("UTF-8")) except UnicodeDecodeError: pass except json.decoder.JSONDecodeError: pass except Exception: raise HTTPError(400) else: if isinstance(body_arguments, dict): for k, v in body_arguments.items(): self.request.arguments.setdefault(k, []).append(v) await super().prepare()
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