python - Flattening an array in Flask API -
i'm making api flask takes post message body nested array, , returns list of values. example curl …. –d ”(([[1, [], [2, 3]], [[4]], 5])” return [1,2,3,4,5]. flattening script works in command line, when post api, weird results. code here:
app = flask(__name__) app.config.from_object(__name__) app.config.from_envvar('phigital_settings', silent=true) @lru_cache(maxsize=500) def flatten(l): flattened = [] el in l: if isinstance(el, (list, tuple)): flattened.extend(flatten(el)) else: flattened.append(el) return flattened @app.route('/flatten', methods=['post']) def flatten_api(): if request.method == 'post': try: return jsonify({"response" : flatten(request.data)}) except exception e: return jsonify({"response" : "error: %s" % str(e)}) if __name__ == '__main__': app.run() testing in postman gets me response: { "response": [ "[", "[", "1", ",", " ", "[", "]", ",", " ", "[", "2", ",", " ", "3", "]", "]", ",", " ", "[", "[", "4", "]", "]", ",", " ", "5", "]" ] }
which not correct. thought might have fact request.data string, tried using ast.literal_eval make request.data list, error "unhashable type: 'list'" when try call flatten on ast.literal_eval(request.data). i'm totally stumped , appreciated.
also, possible in flask return value, rather key value pair? i'd rather return [1,2,3,4,5] rather {"response": [1,2,3,4,5]}
you need use de-serialized data flask. instead of request.data use request.json
change code to:
return jsonify({"response" : flatten(request.json)})
Comments
Post a Comment