def estimate_effects_xml(): """Estimates the effects of COVID-19 and returns data in XML format.""" if not request.json: return jsonify({ "data": request.get_json(), "impact": {}, "severImpact": {}, "errors": { "general": "Json data required" } }), 400 serializer = DataSerializer() try: data = serializer.load(request.get_json()) except ValidationError as err: return jsonify({ "data": request.get_json(), "impact": {}, "severImpact": {}, "errors": err.messages }), 400 xml = dicttoxml(estimator(data)) return Response(response=xml, status=200, mimetype='application/xml')
def estimate_effects(): """Estimates the effect of COVID-19 based on the data passed.""" if not request.json: return jsonify({ "data": request.get_json(), "impact": {}, "severImpact": {}, "errors": { "general": "Json data required" } }), 400 serializer = DataSerializer() try: data = serializer.load(request.get_json()) except ValidationError as err: return jsonify({ "data": request.get_json(), "impact": {}, "severImpact": {}, "errors": err.messages }), 400 return Response(response=json.dumps(estimator(data)), status=200, content_type='application/json')
def get_covid_statistics(): try: data = request.get_json() # To check if the username and password keys have been sent in the request body if data is None: return jsonify({'message': 'No data has been submitted'}), 400 ''' check and see if any of the data is missing in the submitted request ''' if data['periodType'] not in ['days', 'weeks', 'months']: return jsonify({ 'message': 'Period type chosen is wrong; use days, weeks or months' }), 400 ''' We now obtain the data in the submitted and return the estimated covid 19 results ''' return Response(response=dumps(estimator(data)), status=200, content_type='application/json') except Exception as ex: the_logger.log_error('Request error: {0} '.format(ex)) return jsonify({"error": "An error occured during the request"}), 400
def covid_xml(): if request.method == 'POST': print(request.data) data = estimator(sample_data) xml_data = xmltodict.unparse({"data": data}, pretty=True) response = make_response(xml_data) response.headers['Content-Type'] = 'application/xml' return response
def post(self): # arr = [] req_data = request.get_json() res = estimator(req_data) xml = dicttoxml(res, custom_root='response', attr_type=False) xml = xml.decode('utf8').replace("'", '"') # xml = xml.decode('utf8') return xml
def covid_json(): if request.method == "GET": res = Response("", content_type="application/json") return res, 200 if request.method == "POST": data = request.get_json() output = estimator(data) return jsonify(output), 200
def covid_json_estimates(): data_set = request.get_json() for my_dict in data: data_set = my_dict # data_set = dict([ (k,v) for k,v in my_dict.items()] for my_dict in data) result = estimator(data_set) return json.dumps(result)
def xmlApi(): try: if not request.is_json: return jsonify(message=['Invalid or empty data']) jdata = request.json['data'] resp = dicttoxml(estimator(jdata)) return Response(resp, mimetype='application/xml') except: return not_found()
def jsonApi(): try: if not request.is_json: return jsonify(message=['Invalid or empty data']) jdata = request.json['data'] resp = jsonify(estimator(jdata)) resp.status_code = 200 resp.content_type = "application/json" return resp except: return not_found()
def covid_xml_estimates(): data_set = request.get_json() for my_dict in data: data_set = my_dict result = estimator(data_set) xml_result = dicttoxml.dicttoxml(result) new_xml = xml_result.decode("UTF-8") return json.dumps(new_xml)
def test_challenge1(): for [period_type, challenge] in cases: loop = asyncio.get_event_loop() input = loop.run_until_complete(test_utils.mock_estimation_for(period_type)) # nodes from end point data = input["data"] estimate = input["estimate"] output = estimator(data) values = test_utils.value_on_fields(output, estimate, challenge) for [produced, expected] in values: assert test_utils.format_float(produced) == test_utils.format_float(expected)
def covid_xml(): if request.method == "GET": res = Response("", content_type="application/xml") return res, 200 if request.method == "POST": data = request.get_json() output = estimator(data) res = \ Response(dicttoxml( output, attr_type=False), content_type="application/xml") return res, 200
def json_response(): reques_time = time.monotonic() try: data = estimator(request.json) except: data = {} with open('./access.log', 'a') as log: log.write( f'{request.method} \t\t {request.path} \t\t {response.status_code} \t\t {round(time.monotonic()-reques_time, 3)} S \n' ) return data
def process(req_time, route, req_data): try: # pass the request data to the estimator function rsp = estimator.estimator(req_data) # return a json response to the browser rsp_time = datetime.now(tz=timezone.utc).timestamp() * 1000 diff_sec = (rsp_time - req_time) / 1000 log = str(req_time) + "\t\t" + route + "\t\t done in " + str( diff_sec) + " seconds\n" append_log(log) except (TypeError, ValueError): error = {"message": "Invalid data passed"} return error return rsp
def get_estimation_xml(): if request.method == 'POST': req_data = request.get_json() res = dicttoxml(estimator(req_data), attr_type=False) # res = estimator(req_data) # res = dumps({'root': estimator(req_data)}) else: res_dict = { 'message': 'Run POST passing data to receive estimate in xml.' } res = dicttoxml(res_dict, attr_type=False) r = make_response(res) r.headers["Content-Type"] = "application/xml; charset=utf-8" return r, 200, {"Content-Type": "application/xml"}
def estimate_covid19_impact(): """Estimate Covid-19 Impact based on given data""" start = time.clock() data = request.json response = estimator(data) resp = jsonify(response) resp.status_code = 200 request_time = time.clock() - start request_time_data = { "path": "/api/v1/on-covid-19", "time": request_time, "method": "POST", "status_code": resp.status_code, } format_time_logs(request_time_data) return resp
def post(self): parser.add_argument('region', type=str, location='json') parser.add_argument('periodType', type=str, location='json') parser.add_argument('timeToElapse', type=str, location='json') parser.add_argument('reportedCases', type=str, location='json') parser.add_argument('population', type=str, location='json') parser.add_argument('totalHospitalBeds', type=str, location='json') args = parser.parse_args() region_data=str(args.region).replace("'", '"') args['region']= json.loads(region_data); result = mymodule.estimator(args) return jsonify(result)
def estimate_covid19_impact_xml(): """Estimate Covid-19 Impact based on given data and return xml format""" start = time.clock() data = request.json result = estimator(data) xml = dicttoxml(result) xml = xml.decode() resp = Response(xml, status=200, mimetype="application/xml") request_time = time.clock() - start request_time_data = { "path": "/api/v1/on-covid-19/xml", "time": request_time, "method": "POST", "status_code": resp.status_code, } format_time_logs(request_time_data) return resp
def estimate_covid19_impact_json(): """Estimate Covid-19 Impact based on given data and return json format""" if request.headers["Content-Type"] == "application/json": start = time.clock() data = request.json response = estimator(data) resp = jsonify(response) resp.status_code = 200 request_time = time.clock() - start request_time_data = { "path": "/api/v1/on-covid-19/json", "time": request_time, "method": "POST", "status_code": resp.status_code, } format_time_logs(request_time_data) return resp
def xml_response(): reques_time = time.monotonic() response.set_header('content-type', 'text/xml') try: data = estimator(request.json) except: data = {} xml_data = create_xml_from_json(data).toprettyxml() with open('./access.log', 'a') as log: log.write( f'{request.method} \t\t {request.path} \t\t {response.status_code} \t\t {round(time.monotonic()-reques_time, 3)} S \n' ) return xml_data
def post(self): parser.add_argument('region', type=str, location='json') parser.add_argument('periodType', type=str, location='json') parser.add_argument('timeToElapse', type=str, location='json') parser.add_argument('reportedCases', type=str, location='json') parser.add_argument('population', type=str, location='json') parser.add_argument('totalHospitalBeds', type=str, location='json') args = parser.parse_args() region_data=str(args.region).replace("'", '"') args['region']= json.loads(region_data); result = mymodule.estimator(args) xml = jxmlease.emit_xml(result) print(xml) return xml, 200, {'Content-Type': 'text/xml; charset=utf-8'}
def json_fallback_api(): data = { "region": { "name": request.json['region']['name'], "avgAge": request.json['region']['avgAge'], "avgDailyIncomeInUSD": request.json['region']['avgDailyIncomeInUSD'], "avgDailyIncomePopulation": request.json['region']['avgDailyIncomePopulation'] }, "periodType": request.json['periodType'], "timeToElapse": request.json['timeToElapse'], "reportedCases": request.json['reportedCases'], "population": request.json['population'], "totalHospitalBeds": request.json['totalHospitalBeds'] } headers = {"Content-Type": 'application/json', "charset": 'utf-8'} return jsonify(estimator(data)), 200, headers
def covid_json(): return estimator(sample_data)
def covid_default(): return estimator(sample_data)
def get_estimation_default(): req_data = request.get_json() res = estimator(req_data) return jsonify(res)
def post(self): req_data = request.get_json() res = estimator(req_data) return jsonify(res)
def estimate(): if request.method == 'POST': data = request.get_json(force=True) return json.dumps(estimator(data)), { 'Content-Type': 'application/json' }
def estimateXml(): if request.method == 'POST': data = estimator(request.get_json(force=True)) return dicttoxml(data), {'Content-Type': 'application/xml'}
def estimator_view(request, format=None): serializer = EstimatorSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = estimator(serializer.validated_data) return Response(data)
def covid_xml(): data = estimator(sample_data) xml_data = xmltodict.unparse({"data": data}, pretty=True) response = make_response(xml_data) response.headers['Content-Type'] = 'application/xml' return response