Ejemplo n.º 1
0
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')
Ejemplo n.º 2
0
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')
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
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
Ejemplo n.º 5
0
    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
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
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()
Ejemplo n.º 9
0
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()
Ejemplo n.º 10
0
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)
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
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"}
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
    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)    
Ejemplo n.º 18
0
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
Ejemplo n.º 19
0
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
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
    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'} 
Ejemplo n.º 22
0
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
Ejemplo n.º 23
0
    def covid_json():

        return estimator(sample_data)
Ejemplo n.º 24
0
    def covid_default():

        return estimator(sample_data)
Ejemplo n.º 25
0
def get_estimation_default():
    req_data = request.get_json()
    res = estimator(req_data)
    return jsonify(res)
Ejemplo n.º 26
0
    def post(self):
        req_data = request.get_json()
        res = estimator(req_data)

        return jsonify(res)
Ejemplo n.º 27
0
def estimate():
    if request.method == 'POST':
        data = request.get_json(force=True)
        return json.dumps(estimator(data)), {
            'Content-Type': 'application/json'
        }
Ejemplo n.º 28
0
def estimateXml():
    if request.method == 'POST':
        data = estimator(request.get_json(force=True))
        return dicttoxml(data), {'Content-Type': 'application/xml'}
Ejemplo n.º 29
0
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)
Ejemplo n.º 30
0
 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