Course for This Assignment | https://bbs.csdn.net/forums/ssynkqtd-04 |
---|---|
Assignment Requirements | https://bbs.csdn.net/topics/617378696 |
MU STU ID and FZU STU ID | 21125147_832101222 |
Objectives of This Assignment | improve the functions of the previous calculator |
github
frontend : GitHub - localflvcko/frontend
backend : localflvcko/backend (github.com)
目录
Personal Journey and Learnings
psp form
Personal Software Process Stages | Estimated Time(minutes) | Actual Time(minutes) |
Planning | 30 | 30 |
• Estimate | 5 | 5 |
Development | 30 | 30 |
• Analysis | 15 | 100 |
• Design Spec | 30 | 50 |
• Design Review | 30 | 50 |
• Coding Standard | 30 | 50 |
• Design | 150 | 20 |
• Coding | 100 | 50 |
• Code Review | 50 | 30 |
• Test | 50 | 30 |
Reporting | 30 | 30 |
• Test Report | 50 | 50 |
• Size Measurement | 50 | 50 |
• Postmortem & Process Improvement Plan | 100 | 100 |
Sum | 930 | 900 |
calculator display
20231022_140015
databases
20231022_140134
Design
Front-end design:
1. User interface: Create a user interface, usually defined using HTML. This user interface should include input fields for entering numbers, buttons for selecting operations (e.g., adding, subtracting), and a result display area.
2. user input: Using HTML form elements or input boxes, users can enter numbers. These input fields should have unique IDs so that JavaScript can access and process the user input.
3. JavaScript: Use JavaScript to process user input and communicate with the backend. For example, when the user clicks on the add button, JavaScript should capture the value of the input field, package the data into JSON format, and then send the data to a specific route on the backend using AJAX or Fetch API.
4. Result Display: In the user interface, JavaScript is used to receive the calculation results from the backend and display the results on the page.
Backend Design (Flask):
1. Flask Application Create a Flask application to handle front-end requests and perform calculations. You can use the Flask framework to easily create routes and handle HTTP requests.
2. Route Definition: Define routes in your Flask application to handle different operations. For example, you can define a route to handle the sum operation and another to handle the subtract operation. These routes should receive data from the front-end, perform calculations, and then return the results to the front-end.
3. Database Connectivity: If you need to store the results of your calculations to a MySQL database, you will need to add database connectivity code to your Flask application. This may include connecting to a MySQL database server and inserting the results into a database table after the calculation.
4. JSON Response: In Flask routing, the results of the calculation should be returned to the front-end in JSON format. This can be accomplished through Flask's `jsonify` function, which ensures that the front-end can easily parse and display the results.
Overall, front-end design needs to focus on the user interface and interaction with the user, while back-end design needs to handle the computational logic and interaction with the database. Communication between the front-end and back-end usually uses the JSON format. This design idea will help you build a calculator application with front-end and back-end connections.
Code explantion
1.frontend
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计算器</title>
<link rel="stylesheet" href="cal.css">
</head>
<body>
<!-- Calculator Container -->
<div class="calculator">
<input class="show" id="show" placeholder="0">
</div>
<main class="flex">
<!-- Left Panel: Buttons for Operations and Functions -->
<aside class="flex">
<div class="top flex">
<input class="button" type="button" value="CE">
<input class="button" type="button" value="C">
<button class="button" onclick="display('(')">(</button>
<button class="button" onclick="display(')')">)</button>
<input class="button" type="button" value="sqrt">
<input class="button" type="button" value="log">
<button class="button" onclick="switchToDeg()">deg">
<input class="button" type="button" value="x!">
</div>
<div class="num flex">
<input class="button" type="button" value="sin">
<input class="button" type="button" value="7">
<input class="button" type="button" value="8">
<input class="button" type="button" value="9">
<input class="button" type="button" value="cos">
<input class="button" type="button" value="4">
<input class="button" type="button" value="5">
<input class="button" type="button" value="6">
<input class="button" type="button" value="tan">
<input class="button" type="button" value="1">
<input class="button" type="button" value="2">
<input class="button" type="button" value="3">
<button class="button" onclick="switchToRad()">rad">
<input class="button" type="button" value="0">
<input class="button" type="button" value=".">
<input class="button" type="button" value="ans">
</div>
</aside>
<!-- Right Panel: Arithmetic and Equals Buttons -->
<aside class="flex">
<input class="button" type="button" value="%">
<input class="button" type="button" value="/">
<input class="button" type="button" value="*">
<input class="button" type="button" value="-">
<input class="button" type="button" value="+">
<input class="button" type="button" value="=">
</aside>
</main>
<script src="cal.js"></script>
</body>
</html>
var historyData = []; // 存放历史记录
var results = []; // 用于存放结果与历史数据拼接的记录
function append_number(num) {
// 追加数字到显示框
document.form.show.value += num;
return document.form.show.value;
}
function append_operator(op) {
var text = document.form.show.value;
var length = text.length;
// 如果最后一个字符不是数字,则删除最后一个字符
if (text[length - 1] < '0' || text[length] > '9') {
document.form.show.value = text.substring(0, length - 1);
}
// 追加运算符到显示框
document.form.show.value += op;
}
function display_special(op) {
var text = document.form.show.value;
text += op;
document.form.show.value = text;
}
function perform_calculation() {
try {
var expression = document.form.show.value;
if (expression) {
document.form.show.value = eval(expression);
// 处理除以零的情况
if (eval(expression) === Infinity) {
document.form.show.value = "error";
}
var result = eval(expression);
// 发送历史记录到服务器
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://127.0.0.1:5000/get_history', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
const data = {
expression: expression,
result: result
};
xhr.send(JSON.stringify(data));
}
} catch {
document.form.show.value = "error";
}
}
function clear_display() {
// 清空显示框
document.form.show.value = "";
}
function calculate_sin() {
perform_calculation();
var angle = document.form.show.value;
var sinValue = Math.sin(angle / 180 * Math.PI);
sinValue = sinValue.toFixed(2);
clear_display();
document.form.show.value += sinValue;
}
function calculate_cos() {
perform_calculation();
var angle = document.form.show.value;
var cosValue = Math.cos(angle / 180 * Math.PI);
cosValue = cosValue.toFixed(2);
clear_display();
document.form.show.value += cosValue;
}
function calculate_tan() {
perform_calculation();
var angle = document.form.show.value;
var tanValue = Math.tan(angle / 180 * Math.PI);
tanValue = tanValue.toFixed(2);
clear_display();
document.form.show.value += tanValue;
}
function calculate_ln() {
perform_calculation();
document.form.show.value = Math.log10(document.form.show.value);
}
function remove_last_character() {
// 删除最后一个字符
var text = document.form.show.value;
var length = text.length;
document.form.show.value = text.substring(0, length - 1);
}
function calculate_sqrt() {
perform_calculation();
document.form.show.value = Math.sqrt(document.form.show.value);
}
function calculate_factorial(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
function calculate_factorial_and_display() {
perform_calculation();
document.form.show.value = calculate_factorial(document.form.show.value);
}
function handle_operation(str) {
if (str >= '0' && str <= '9') {
append_number(str);
}
if (str === '+' || str === '*' || str === '/' || str === '-' || str === '.' || str === '%') {
append_operator(str);
}
if (str === 'sin') {
calculate_sin();
}
if (str === 'cos') {
calculate_cos();
}
if (str === 'tan') {
calculate_tan();
}
if (str === 'ln') {
calculate_ln();
}
if (str === 'x!') {
calculate_factorial_and_display();
}
if (str === '=') {
perform_calculation();
}
if (str === 'AC') {
clear_display();
}
if (str === 'sqrt') {
calculate_sqrt();
}
if (str === 'BACK') {
remove_last_character();
}
return document.form.show.value;
}
function fetch_history() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:5000/get_calculation', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
data = JSON.parse(xhr.responseText);
records = data['data'];
let historyText = "";
for (let i = 0; i < records.length; i++) {
historyText += records[i][0] + " = " + records[i][1] + "\n";
}
document.form.show.value = historyText;
}
}
};
xhr.send();
}
.calculator {
height: 80px;
width: 250px;
background-color: #3498db; /* 蓝色背景 */
}
#dots {
display: flex;
}
.button {
height: 50px;
width: 50px;
color: #fff; /* 白色字体 */
font-size: large;
}
.show {
display: flex;
flex-direction: row-reverse;
height: 50px;
width: 242px;
font-size: 2em;
color: #e74c3c; /* 红色字体 */
margin-top: 7px;
margin-right: 2px;
}
.form {
color: #f1c40f; /* 黄色字体 */
}
.flex {
display: flex;
}
.dot {
height: 13px;
width: 13px;
border-radius: 50%;
margin-left: 5px;
margin-top: 5px;
}
#top .button {
background-color: #27ae60; /* 绿色按钮背景 */
}
#num .button {
background-color: #8e44ad; /* 紫色按钮背景 */
}
aside-right .button {
background-color: #f39c12; /* 橙色按钮背景 */
}
main {
width: 250px;
height: 300px;
flex-wrap: wrap;
}
#num {
flex-wrap: wrap;
}
#top {
flex-wrap: wrap;
}
aside-right {
flex-direction: column;
}
aside-left {
width: 200px;
flex-direction: row;
flex-wrap: wrap;
}
2.backend
from flask import Flask, request, jsonify
from flask_cors import CORS
import pymysql
import datetime
db_connection = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='123456',
database='calculator'
)
app = Flask(__name__)
CORS(app)
db_cursor = db_connection.cursor()
@app.route('/record_history', methods=['POST'])
def record_history():
data = request.get_json()
expression = data.get('expression')
result = data.get('result')
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data_tuple = (current_time, expression, result)
insert_query = "INSERT INTO alan_calculate VALUES (%s, %s, %s)"
db_cursor.execute(insert_query, data_tuple)
db_connection.commit()
response_message = "Recorded successfully"
return jsonify({"message": response_message})
@app.route('/fetch_calculations', methods=['GET'])
def fetch_calculations():
db_cursor.execute("SELECT expression, result FROM alan_calculate ORDER BY time DESC LIMIT 10")
data = db_cursor.fetchall()
return jsonify({"data": data})
if __name__ == '__main__':
app.run(debug=True)
Personal Journey and Learnings
1. Technical challenges:
In this project, I faced both front-end and back-end technical challenges. The front-end part involved HTML, CSS, and JavaScript, and I needed to create an intuitive user interface and make sure that the data was passed correctly to the back-end. The backend used the Flask framework, which was a new learning opportunity for me, but also provided me with a powerful tool to handle HTTP requests and database connections.
2. database integration:
Integration with MySQL database was an important aspect. I learned how to establish database connections, create tables to store calculations, and write SQL queries to insert and retrieve data. This gave me a better understanding of how databases work.
3. front-end and back-end communication:
Understanding how to implement front-end and back-end communication is key. I learned how to pass data using the JSON format and how to send data to the backend using JavaScript's Fetch API. This also opened the door to web development, allowing me to build more complex applications.
4. Continuous learning:
After this project, I learned that in technology, learning never ends. New technologies and tools emerge every day, so it is important to stay sensitive to new knowledge. I plan to continue learning and improving my skills.
Overall, this calculator project was a major milestone in my technical growth. Not only did I acquire front-end and back-end development skills, but I also learned how to face challenges, solve problems, and continue to improve myself. This experience was not only a project, but also a journey full of lessons and accomplishments that will continue to shape my career. I look forward to future projects and continuing to explore and learn.