def parse_boolean(value): """Try parse boolean. raises UserError if unable. """ if isinstance(value, bool): return value elif value.lower() == "true": return True elif value.lower() == "false": return False else: raise UserError("Boolean value not one of [true, false]")
def parse_request_yaml(): """Returns a python representation of a YAML POST body. :raises: UserError if any exception is raised parsing the YAML body """ raw = request.get_data() try: return yaml.safe_load(raw) except Exception as e: raise UserError("Unable to parse yaml: {}".format(e))
def parse_json(raw): """Returns a python representation of a JSON document. :param str raw: Load this provided string. :raises: UserError if any exception is raised parsing the JSON body ..note:: Uses :func:`oph_raise_for_duplicates` in parser. """ try: return simplejson.loads(raw, object_pairs_hook=oph_raise_for_duplicates) except Exception as e: raise UserError("Unable to parse json: {}".format(e))
def parse_request_json(expected_types=(dict, list)): """Returns a python representation of a JSON POST body. :param str raw: Load this provided string. If raw is not provided, pull the body from global request object :raises: UserError if any exception is raised parsing the JSON body :raises: UserError if the result is not of the expected type """ parsed = parse_json(request.get_data()) if not isinstance(parsed, expected_types): raise UserError( "JSON parsed from request is an invalid type: {}".format( parsed.__class__.__name__)) return parsed
def handlers(ct): if "application/x-www-form-urlencoded" in ct: # Converts the immutable multi-dict (class type of request.form) into a regular dict, # because somewhere downstream this parsed options is checked and sanitized, where # mutation occurs which throws an exception (for modifying an immutable). # dict returns a regular dictionary; however, because the source is a multi-dict, # all values are converted into a list (because form fields can be repeated for # multi-value fields). Here we unbox the value for lists of one single element and # let the ones with multiple values remain as lists. return { key: value if len(value) > 1 else value[0] for key, value in dict(request.form).items() } elif "application/json" in ct: return request.get_json() if request.data != "" else {} else: error_out( UserError( "Content-Type header for POST must be 'application/json' or 'application/x-www-form-urlencoded'" ))