目录
I.Introduction
This task is mainly to add functions to the calculator of job 1 to achieve more expanded functions, and store the input string and results in the back-end database, using the technology of back-end separation to complete this task. Based on the Html, Css and Javascript of job 1 as the front end, I will use flask framework in python library and Mysql database to complete data transmission and reading at the back end.
Link to the finished project code:
Front end: https://github.com/ThestarRYz/SE-EE301-Calculator-front-end
Back end: https://github.com/ThestarRYz/SE-EE301-Calculator-back-end
II.Personal Information
The link of my Class | https://bbs.csdn.net/forums/ssynkqtd-04 |
---|---|
The link of requirement of this Assignment | https://bbs.csdn.net/forums/ssynkqtd-04 |
The Aim of this Assignment | Website Calculator |
MU STU ID and FZU STU ID | 21126712_832102213 |
III. PSP Table
Personal Software Process Stages | Estimated Time(minutes) | Actual Time(minutes) |
---|---|---|
Planning | ||
• Estimate | 40 | 40 |
Development | ||
• Analysis | 40 | 50 |
• Design Spec | 20 | 25 |
• Design Review | 15 | 15 |
• Coding Standard | 20 | 20 |
• Design | 30 | 30 |
• Coding | 130 | 130 |
• Code Review | 40 | 40 |
• Test | 30 | 25 |
Reporting | 70 | 100 |
• Test Repor | 20 | 20 |
• Size Measurement | 20 | 20 |
• Postmortem & Process Improvement Plan | 30 | 30 |
Sum | 505 | 545 |
IV.Thoughts before doing the project
Before doing this assignment, I first enriched the basic functions of the original front-end, realized more expanded functions, and slightly beautified the appearance of the design. About the back end, I went to the Internet to find a lot of knowledge about the back end and database, and learned that there are a lot of framework structures in the back end, and finally chose flask framework to learn the basic knowledge of this framework and the basic knowledge of MySQL database, and then studied how to link the front end, the back end framework and the database.
V.Design and implementation process
To clarify in advance, the functions that have been implemented and written in homework 1, the relevant code will not appear in this homework, I will show some code to expand the function and the front and back end, how to link the database, and the back end code.
See the GitHub link at the beginning for detailed code.
VI.Code description
Extended function: scientific calculator
Calculate radical symbols, trigonometric functions, logarithms, scientific notation.
function sqrt() {
str = document.getElementById("text");
var number = eval(str.value);
result = Math.sqrt(number);
str.value = result;
}
function log() {
str = document.getElementById("text");
var number = eval(str.value);
result = Math.log10(number);
str.value = result;
}
function exponential() {
var str = document.getElementById("text").value;
if (str === "") {
document.getElementById("text").value = Math.E;
} else {
document.getElementById("text").value += Math.E;
}
}
function pi() {
var str = document.getElementById("text").value;
if (str === "") {
document.getElementById("text").value = Math.PI;
} else {
document.getElementById("text").value += Math.PI;
}
}
function E() {
var str = document.getElementById("text").value;
var num = parseFloat(str);
var result = num.toExponential();
document.getElementById("text").value = result;
}
In homework 1, basic operations have been implemented, such as addition, subtraction, multiplication, division, and remainder. These are some ways to expand.(Note: The implementation of bracket calculation has been implemented in assignment 1.)
About the backend
from flask import Flask, jsonify, request
import pymysql
from flask_cors import CORS
app = Flask(__name__)
cors = CORS(app)
# MySQL数据库连接配置
db = pymysql.connect(
host='localhost',
user='root',
password='1234567z',
database='calculator_db'
)
cursor = db.cursor()
# 创建数据库表
def create_table():
sql = """CREATE TABLE IF NOT EXISTS history (
id INT AUTO_INCREMENT PRIMARY KEY,
expression VARCHAR(255) NOT NULL,
result DECIMAL(10,2) NOT NULL
)"""
cursor.execute(sql)
db.commit()
# 插入历史记录
def insert_history(expression, result):
sql = "INSERT INTO history (expression, result) VALUES (%s, %s)"
cursor.execute(sql, (expression, result))
db.commit()
# 获取历史记录
def get_history():
sql = "SELECT * FROM history ORDER BY id DESC LIMIT 10"
cursor.execute(sql)
data = cursor.fetchall()
return data
# 路由:获取历史记录API
@app.route('/api/calculator/history', methods=['GET'])
def get_history_api():
data = get_history()
history = [{'id': item[0], 'expression': item[1], 'result': float(item[2])} for item in data]
return jsonify({
"code": 200,
"message": "ok",
"data": {
"history": history
}
})
@app.route('/api/calculator/history', methods=["POST"])
def store_result():
expression = request.form.get("expression")
result = request.form.get("result")
print(expression, result)
insert_history(expression, result)
return jsonify({
"code": 200,
"message": "ok",
"data": None
})
if __name__ == '__main__':
create_table()
app.run()
This Python code is a Flask application that provides an API for a calculator history feature. It connects to a MySQL database to store and retrieve calculation history. Here’s an explanation of the code:
-
Imports:
Flask
: Imports the Flask framework for creating a web application.jsonify
: A helper function provided by Flask for returning JSON responses.request
: Allows access to HTTP request data.pymysql
: A Python MySQL client library for interacting with MySQL databases.CORS
: Cross-Origin Resource Sharing support for handling requests from different domains.
-
Flask App Configuration:
app = Flask(__name__)
: Creates a Flask application instance.
-
CORS Configuration:
cors = CORS(app)
: Initializes CORS support for handling cross-origin requests.
-
Database Connection:
- Establishes a connection to a MySQL database using
pymysql
.
- Establishes a connection to a MySQL database using
-
Database Cursor:
- Creates a cursor object for executing SQL queries.
-
Database Table Creation:
create_table()
: Defines a function to create a table namedhistory
if it doesn’t exist already. This table has columns forid
(auto-incrementing primary key),expression
, andresult
.
-
Inserting History:
insert_history(expression, result)
: Inserts a new record into thehistory
table with the providedexpression
andresult
.
-
Getting History:
get_history()
: Retrieves the 10 most recent records from thehistory
table.
-
API Endpoints:
-
@app.route('/api/calculator/history', methods=['GET'])
: Defines an endpoint for getting calculator history.- It calls
get_history()
to retrieve data and returns it as JSON.
- It calls
-
@app.route('/api/calculator/history', methods=["POST"])
: Defines an endpoint for storing calculator results.- It extracts
expression
andresult
from the HTTP request and callsinsert_history()
to save the data.
- It extracts
-
-
Main Execution:
if __name__ == '__main__':
: Executes when the script is run directly (not imported as a module).- Calls
create_table()
to ensure the table exists. - Starts the Flask app with
app.run()
.
Overall, this code sets up a Flask web application with routes to handle GET and POST requests for calculator history. It connects to a MySQL database to store and retrieve history records. The application also has CORS support enabled, allowing it to handle requests from different domains.
Links about front-end and back-end
This part will implement the input string and store the results in the back-end database. You can use the button to return to the previous calculation results, and view the history to read the last ten string formulas and corresponding calculation results, while linking the front and back ends.
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
function store(expression, result) {
console.log(expression, result)
$.ajax({
url: 'http://localhost:5000/api/calculator/history',
type: 'post',
data: {
expression: expression,
result: result
}
});
}
function getHistory() {
$.ajax({
url: 'http://localhost:5000/api/calculator/history',
type: 'get',
success: function (res) {
console.log(res);
// 创建表格
var table = $('<table>').addClass('history-table');
// 创建表头
var headerRow = $('<tr>');
headerRow.append($('<th>').text('ID'));
headerRow.append($('<th>').text('Formula'));
headerRow.append($('<th>').text('Result'));
table.append(headerRow);
// 填充数据
for (var i = 0; i < res.length; i++) {
var row = $('<tr>');
row.append($('<td>').text(res[i].id));
row.append($('<td>').text(res[i].formula));
row.append($('<td>').text(res[i].result));
table.append(row);
}
// 将表格添加到页面中
$('#history').html('');
$('#history').append(table);
}
});
}
function getAnswer() {
$.ajax({
url: 'http://localhost:5000/api/calculator/history',
type: 'get',
success: function (res) {
console.log(res["data"]["history"][0]["result"]);
var value = res["data"]["history"][0]["result"];
$('#text').val(value); // 将结果放到输入框中
}
});
}
This JavaScript code is responsible for interacting with a web page that utilizes the Flask application you provided earlier. Here’s an explanation of the code:
-
jQuery Library:
script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"
: Includes the jQuery library. jQuery is a fast, small, and feature-rich JavaScript library that simplifies interactions with the DOM and handles AJAX requests.
-
store
function:- This function is responsible for sending a POST request to the server to store calculator results.
- It takes two parameters:
expression
andresult
, which represent the mathematical expression and its computed result. - Uses
$.ajax
to make an asynchronous HTTP request to the specified URL (http://localhost:5000/api/calculator/history
). - The request type is set to
post
, and the data being sent is an object containingexpression
andresult
. - This function is used for saving calculation history.
-
getHistory
function:- This function is triggered when a user requests to view the calculation history.
- It sends a GET request to
http://localhost:5000/api/calculator/history
. - Upon success, it processes the response (
res
), which is expected to contain an array of history records. - It dynamically creates an HTML table to display the history and appends it to the element with the ID
history
.
-
Creating the History Table:
- The
getHistory
function dynamically creates an HTML table with headers (ID, Formula, Result) and fills it with data retrieved from the server.
- The
-
getAnswer
function:- This function is used to retrieve the most recent calculation result from the server.
- It sends a GET request to
http://localhost:5000/api/calculator/history
. - Upon success, it extracts the result from the response and updates an input field with the ID
text
to display this value.
Overall, this JavaScript code works in conjunction with the Flask application to handle user interactions on a web page. It uses AJAX to send requests to the server, receive responses, and update the page dynamically without requiring a full page refresh.
About the MySQL
Optimization of CSS
body {
background:url(https://img1.baidu.com/it/u=1436390931,763795453&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=1082);
}
Product display:
video2
VII.Conclusion
This assignment is mainly to realize the separation of front-end and back-end, iteratively upgrade the basic calculator I made before, to achieve more expansion functions and to link and access the database. In this task, I learned the python flask framework and MySQL. The connection and application, and finally link the front and back ends to create a calculator with separate front and back ends.