Front-End and Back-End Separated Calculator System Development_832402110_廖伟镔
Front-End and Back-End Separated Calculator System Development
1.GitHub Repositories and Code Style
- Frontend Repository: https://github.com/kaaJ4K/calculator_frontend
- Backend Repository: https://github.com/kaaJ4K/calculator_backend
The project source code is managed using Git and GitHub.
2.Design and Implementation
2.1.Overall architecture
┌──────────────┐ HTTP / JSON ┌───────────┐
│ Front end │ ───────────→ │ Back end │
│ HTML/CSS/JS │ │ HttpServer │
│ UI & events │ ←─────────── │ controller │
└──────────────┘ JSON response │ ↓ │
│ service layer │
│ ↓ │
│ expression core│
│ ↓ │
│ SQLite database│
└───────────┘
2.2
The calculator system is divided into several functional modules. Each module has a specific responsibility and works together to provide a complete calculation service. The functional structure is shown below:
Calculator System
│
├── User Interface Module
│ ├── Calculator Display
│ ├── Number Input
│ ├── Operator Input
│ ├── Expression Display
│ └── Result Display
│
├── Calculation Module
│ ├── Basic Arithmetic Operations
│ │ ├── Addition (+)
│ │ ├── Subtraction (-)
│ │ ├── Multiplication (*)
│ │ └── Division (/)
│ │
│ ├── Expression Processing
│ │ ├── Operator Priority
│ │ ├── Parentheses Processing
│ │ └── Decimal Number Support
│ │
│ └── Error Handling
│ ├── Division by Zero
│ └── Invalid Expression
│
├── API Communication Module
│ ├── Send Calculation Request
│ ├── Receive JSON Response
│ ├── Health Check API
│ └── History API
│
├── History Management Module
│ ├── Save Calculation Records
│ ├── Load History
│ ├── Delete Single Record
│ └── Clear History
│
└── Database Module
├── Database Initialization
├── Store Expression
├── Store Result
└── Store Timestamp
2.3.API Design
Main API endpoints:
POST /api/calculate
Purpose: Calculate an expression and save the result.
GET /api/history
Purpose: Retrieve calculation history.
DELETE /api/history/{id}
Purpose: Delete a specific history record.
DELETE /api/history
Purpose: Clear all history records.

API testing
2.4.Database design
I chose SQLite for this project. As a single-file database, it requires no standalone database server and operates via the sqlite-jdbc driver, making it a suitable choice.
The database stores:
| Field | Description |
|---|---|
| id | Unique record identifier |
| expression | User input expression |
| result | Calculation result |
| timestamp | Calculation time |
2.5.Error handling
Expression-level errors (divide by zero, mismatched parentheses, unknown function, out-of-domain argument, etc.) raise CalculationException with Chinese error messages and error positions. The controller handles the exception and returns HTTP 400 with {"success":false,"message":...} for frontend display. Database failures → 500; deletion of non-existent ID → 404. All responses have CORS headers to support standalone frontend deployment.
2.6.Live Demo

3.Working Demo
All screenshots below are real running captures of the project.
3.1.Main interface
This is what you see when you open the site: the calculator on the left, the history panel on the right.

3.2. Addition
1+2=3
3.3. Subtraction
15-7=8

3.4. Multiplication
8*9=72

3.5. Division
72/8=9

3.6. Decimal calculation
0.1+0.2.With raw floating-point this would print as 0.30000000000000004. The back end uses BigDecimal when formatting the output, so it displays 0.3.

3.7.Compound expression (operator precedence)
1+2*3=7 
3.8. Parentheses
(1+3)*5=20

3.9. Unary minus
-5+8=3

3.10. Minus after an operator
3×-2 = -6

3.11. Division by zero
the back end returns the error message Division by zero"

3.12. Invalid expression
2+*3 is rejected with an error message and the position of the mistake.

3.13.History

3.14.Delete one record
Click the × on the right of an entry; that row is deleted from the database and disappears from the list

3.15. History survives a restarte
After I stopped the back-end, restarted it, and refreshed the page, the records were still there — because they live in the back-end SQLite database file, not in the browser.

16.Clear all history

4. Code Explanation
4.1Backend Calculation API (app.py)
@app.route("/api/calculate", methods=["POST"])
def calculate():
data = request.get_json()
expression = data.get("expression")
try:
result = calculate_basic(expression)
save_history(expression, result)
return jsonify({
"success": True,
"expression": expression,
"result": result
})
except Exception as e:
return jsonify({
"success": False,
"message": str(e)
}), 400
This API is the core calculation interface of the backend.
The front-end sends a mathematical expression in JSON format through an HTTP POST request. The backend first extracts the expression from the request data.
After receiving the expression, the backend calls the calculation module to process the expression and generate the result.
4.2 Expression Calculation Module (calculator.py)
def calculate_basic(expression):
if "+" in expression:
a, b = expression.split("+")
return float(a) + float(b)
if "-" in expression:
a, b = expression.split("-")
return float(a) - float(b)
if "*" in expression:
a, b = expression.split("*")
return float(a) * float(b)
if "/" in expression:
a, b = expression.split("/")
if float(b) == 0:
raise ValueError("Division by zero")
return float(a) / float(b)
raise ValueError("Invalid expression")
Explanation
The calculation module is responsible for processing mathematical expressions.
The function checks the operator contained in the expression and performs the corresponding mathematical operation.
For division operations, the program performs an additional validation to prevent division by zero errors.
When the expression format is invalid, the function raises an exception. The exception will be handled by the API layer and returned to the front-end.
This modular design separates calculation logic from the Flask application, making the program easier to maintain and test.
4.3 Database Insertion for Calculation History
def save_history(expression, result):
cursor.execute(
"""
INSERT INTO history
(expression, result, created_at)
VALUES (?, ?, datetime('now'))
""",
(expression, result)
)
conn.commit()
Explanation
This function is responsible for saving successful calculations into the backend database.
Each calculation record stores three important pieces of information:
- The original expression entered by the user
- The calculation result
- The calculation time
The database operation uses parameterized SQL queries to avoid directly inserting user input into SQL statements.
After inserting the record, commit() permanently saves the data.
This allows the calculation history to remain available even after the user refreshes the webpage.
4.4 History Query API
@app.route("/api/history", methods=["GET"])
def get_history():
records = query_history()
return jsonify(records)
Explanation
This API provides the calculation history function.
When the front-end requests the history list, the backend queries the database and returns all stored calculation records in JSON format.
The front-end does not store history locally. Instead, all history data comes from the backend database, which ensures data persistence.
4.5 Front-End API Request (app.js)
async function calculateExpression(expression){
const response = await fetch(
"/api/calculate",
{
method:"POST",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
expression: expression
})
}
);
const data = await response.json();
displayResult(data.result);
}
Explanation
This function handles communication between the front-end and backend.
The front-end sends the user's expression to the backend using the Fetch API.
The request uses the POST method and JSON format because the expression needs to be processed by the backend service.
After receiving the response, the front-end extracts the returned result and updates the user interface.
This implementation demonstrates the front-end/back-end separation architecture used in this project.
5.PSP Table
| PSP Task | Estimated Time (min) | Actual Time (min) |
|---|---|---|
| Requirement Analysis | 60 | 50 |
| System Design | 90 | 100 |
| Front-end Development | 240 | 260 |
| Back-end Development | 240 | 280 |
| Expression Calculation Module | 180 | 200 |
| Database Design | 60 | 70 |
| Calculation History Module | 90 | 100 |
| Front-end / Back-end Integration | 120 | 150 |
| Testing and Debugging | 180 | 220 |
| Deployment (PythonAnywhere) | 120 | 180 |
| Blog Writing | 120 | 150 |
| Other Work | 60 | 80 |
| Total | 1560 | 1840 |
I spent about five hours more than estimated. The extra time mainly went into front-end/back-end integration, debugging, and deployment configuration. These issues took additional time to solve, especially during API communication and PythonAnywhere deployment, which I explain in the last section.
6. Problem I Meet and What I Learned
Problem I Meet
6.1 Python Environment Setup
At the beginning of the development, I had problems with the Python environment. The python command did not work correctly, and the project could not run because the required packages were not installed in the correct environment.
The fix was creating a virtual environment and installing all required dependencies, including Flask and Flask-CORS. After activating the virtual environment, the backend could run normally.
This experience helped me understand the importance of isolated development environments and dependency management.
6.2 Flask Import Error
During backend development, the Flask application failed to start because the calculation module could not be imported correctly.
The problem was caused by the function name and file structure not matching the import statement. The backend tried to import a function that was not available in the calculator module.
The fix was checking the module structure carefully, updating the function name, and making sure the backend files had a clear organization.
This taught me that a good project structure and consistent naming are important for maintaining Python applications.
6.3 Front-end and Back-end Communication
At first, the front-end and back-end were running separately on local machines. The front-end needed to send requests to the Flask API, but the communication failed because the API address and request configuration were incorrect.
The problem was solved by checking the API endpoints, updating the request URL, and configuring CORS support on the backend.
After fixing this issue, the front-end could successfully send expressions to the backend and receive calculation results.
I learned how front-end and back-end systems communicate through HTTP requests and JSON data.
6.4 Database Persistence Problem
The calculator could calculate results correctly, but the history function required storing calculation records permanently.
The solution was adding database operations after every successful calculation. The backend stores the expression, result, and calculation time into SQLite, and the history API retrieves these records from the database.
This helped me understand that persistent data should be handled by the backend instead of relying on front-end storage.
6.5 PythonAnywhere Deployment Configuration
The project worked correctly on my local computer, but the first deployment to PythonAnywhere showed the default PythonAnywhere page instead of my application.
The problem was caused by incorrect Web App configuration. The source code path, virtual environment path, and WSGI configuration were not pointing to the Flask project correctly.
The fix was updating the WSGI file, configuring the correct project directory, setting the virtual environment, and reloading the web application.
After these changes, the backend became publicly accessible through PythonAnywhere.
This taught me that deployment requires not only working code but also correct server configuration.
6.6 API Testing and Debugging
During testing, I needed to verify whether each backend function worked correctly.
I tested the system using API requests:
/api/healthto check whether the backend was running/api/calculateto verify expression calculation/api/historyto verify database retrieval
Through these tests, I found and fixed problems step by step instead of debugging the whole system at once.
I learned the importance of testing individual modules and using API responses to locate problems quickly.
What I Learned
Through this project, I gained a better understanding of the complete development process of a web application.
I finally understood the relationship between the front-end and back-end: the front-end is responsible for user interaction and display, while the back-end handles business logic, calculation processing, and database operations. They communicate through HTTP APIs and JSON data.
I also learned how to build a Flask backend, design REST APIs, store data using SQLite, handle exceptions, and deploy a web application to a public server.
The deployment process was especially valuable because it allowed me to experience the complete workflow:
Development
↓
Testing
↓
Debugging
↓
Deployment
↓
Public Access
Problems such as environment configuration, API communication, database persistence, and deployment settings became practical experiences rather than only theoretical concepts.
Possible future improvements include adding user accounts, improving expression parsing, adding calculation history search, and supporting more advanced scientific calculations.
相关推荐
题解:AtCoder AT_awc0031_e Power Grid Blackout Crisis
对于每个事件发生后的即时状态,判断所有工厂是否能够获得必要的电力并继续运营。也就是说,在每个事件后,回答是否存在一种电力路由方式,使得仅使用当前运行的发电厂,满足流量守恒条件,并且每个工厂。题目涵盖了从基础到进阶的多种算法和数据结构,旨在为不同阶段的编程学习者提供一条清晰、平稳的学习提升路径。个发电厂都在运行,但无法保证即使在初始状态下所有工厂都能获得必要的电力。然而,由于老化,发电厂预计会依次故障并停机。即使有盈余电力流入,工厂也能正常运行。在每个地点,电力平衡必须满足流量守恒。的总流量,对连接到地点。
基于MATLAB的复合弹性模量分析,采用混合法则,结合纤维体积分数变化和图形结果。.zip
1.版本:matlab2014a/2019b/2024b 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。
基于MATLAB的自适应纯追踪曲线跟踪机器人仿真,采用多路径、自适应速度控制和图形界面可视化。.zip
1.版本:matlab2014a/2019b/2024b 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。
【数据库优化】通信行业B/O域查询性能提升:基于分区裁剪与覆盖索引的秒级溯源系统实现
内容概要:本文围绕通信行业中海量话单与信令数据的查询性能问题,系统阐述了从全表扫描到秒级响应的数据库优化路径。文章以运营商 cdr_detail 表为案例,揭示了因使用函数操作索引列(如DATE(call_start_time))和深分页(LIMIT offset, size)导致的全表扫描问题,并提出完整的优化方案:通过时间范围RANGE分区实现分区裁剪、构建msisdn与时间的联合覆盖索引、消除索引列函数运算、采用游标分页替代OFFSET等方式,使查询性能从P95 8.3秒降至290毫秒。同时介绍了执行计划分析(EXPLAIN)在调优中的关键作用,并展望了HTAP架构、向量化执行与AI自治优化器等未来方向。; 适合人群:具备一定数据库基础知识,从事通信行业数据开发、DBA或后端研发的技术人员,尤其是面对大规模时序数据查询性能瓶颈的工程师;; 使用场景及目标:①解决营业厅用户详单查询、网间结算对账、VoNR信令分析等高并发、低延迟查询场景下的性能问题;②掌握如何通过分区策略、索引设计和SQL改写实现从全表扫描到精准索引访问的优化落地; 阅读建议:建议结合实际生产环境中的大表查询案例,对照本文的反例与正例进行执行计划对比分析,并在测试环境中实践分区表创建、覆盖索引构建及游标分页改写,深入理解每项优化技巧的实际效果。
石墨提纯全球市场结构与产业发展趋势分析报告(QYResearch最新研究).docx
石墨提纯全球市场结构与产业发展趋势分析报告(QYResearch最新研究)



