generated from BuildforSDG-Cohort1-Assessment/covid-19-estimator-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
97 lines (75 loc) · 2.32 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# Challenge 5
import os
import logging
import time
from flask import Flask, request, g, jsonify, Response
from src.estimator import estimator
from dicttoxml import dicttoxml
if "logs.txt" in os.listdir():
os.remove("logs.txt")
app = Flask(__name__)
# initialise log save file
logging.basicConfig(filename="logs.txt", level=logging.INFO)
@app.before_request
def get_time():
"""
Get time before request
"""
g.start = time.time()
@app.route("/api/v1/on-covid-19/", methods=["GET", "POST"])
@app.route("/api/v1/on-covid-19/json", methods=["GET", "POST"])
def json_index():
"""
Handles 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
@app.route("/api/v1/on-covid-19/xml", methods=["GET", "POST"])
def xml_index():
"""
Handles 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
@app.route("/api/v1/on-covid-19/logs", methods=["GET", "POST"])
def logs_index():
"""
Handles Logging
"""
if request.method != "GET":
return Response("Method not arrowed", mimetype="text/plain", status=405)
data_logs = [] # logging list
with open("logs.txt", "rt") as f: # read logs file and take cycles
data = f.readlines()
for line in data:
if "root" in line and "404" not in line:
data_logs.append(line[10:])
return Response("".join(data_logs), mimetype="text/plain")
@app.after_request
def log_request_info(response):
"""
Gets response as input and returns the logging
details
"""
difference = int((time.time() - g.start) * 1000)
status_code = response.status.split()[0]
logging.info(
f"{request.method}\t\t{request.path}\t\t{status_code}\t\t{str(difference).zfill(2)}ms\n"
)
return response
if __name__ == "__main__":
app.run(debug=True)