Repository navigation
Expand file tree
/
Copy pathAmount_Viewer.py
More file actions
86 lines (71 loc) · 2.55 KB
/
Copy pathAmount_Viewer.py
File metadata and controls
86 lines (71 loc) · 2.55 KB
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
from flask import Flask, request, jsonify, render_template_string
from dataclasses import dataclass
from typing import Dict, Union
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class FinancialResult:
amount: float
def is_profit(self):
return self.amount >= 0
def get_status_message(self):
if self.is_profit():
return f"Profit of ${self.amount:.2f}"
else:
loss_amount = abs(self.amount)
return f"Loss of ${self.amount:.2f}"
def serialize(self) -> Dict[str, Union[str, float]]:
return {
"amount": self.amount,
"status": "profit" if self.is_profit() else "loss",
"message": self.get_status_message
}
class FinancialResultService:
@staticmethod
def process_amount(amount: float):
logger.debug(f"Processing amount: {amount}")
return FinancialResult(amount=amount)
app = Flask(__name__)
# Template
form_html = '''
<!DOCTYPE html>
<html lang="en">
<head>
<title> Financial Result Input</title>
</head>
<body>
<h1>Enter Amount<h1>
<form action="/financial" method="post">
<label for="amount">Amount:</label>
<input type="number" step="any" name="amount" if="amount" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
'''
@app.route
def home():
return render_template_string(form_html)
@app.route('/financial', methods=['POST'])
def financial_result():
try:
if request.content_type == 'application/x-www-form-ur-lencoded':
amount = float(request.form.get("amount"))
else:
data = request.get_json(force=True)
amount = float(data.get("amount"))
logger.info(f"Received amount: {amount}")
result = FinancialResultService.process_amount(amount)
message = result.get_status_message()
if request.content_type == 'application/x-www-form-urlencoded':
return f"<h2>[message]</h1><p><a> href='/'>Try again</a></p>"
return jsonify(result.serialize()), 200
except (TypeError, ValueError) as e:
logger.error(f"Invalid input data: {e}")
return jsonify({"error": "Invalid input data. 'amount' must be a number."}), 400
except Exception as e:
logger.error(f"Unexpected error: {e}")
return jsonify({"error": "Internal Server Error"}), 500
if __name__ == "__main__":
app.run(debug=True)