First Assignment: xxr Calculator — A Front-End and Back-End Separation Calculator_832402102郭诗迅

832402102郭诗迅 2026-09-28 20:30:02

First Assignment: xxr Calculator — A Front-End and Back-End Separation Calculator System

ItemDescription
CourseSoftware Engineering
AssignmentFront-End and Back-End Separation Calculator System
ObjectiveBuild a calculator with HTTP APIs, secure server-side calculation, and persistent history storage
Assignment referenceFirst Assignment — Front-End and Back-End Separation Calculator System

Table of Contents

GitHub Repositories and Code Standards

The front end uses plain HTML, CSS, and JavaScript. Its coding style is based on the Google JavaScript Style Guide. The back end uses Python and follows PEP 8. Both repositories contain a README.md and a codestyle.md file.

PSP Table

PSP StageEstimated Time (minutes)Actual Time (minutes)
Reading the assignment and requirement analysis4540
Architecture, API, and database design6060
Front-end refactoring12080
Back-end calculator module150120
SQLite history module6080
Front-end and back-end integration9090
Testing and bug fixing9070
Deployment6050
Blog writing and screenshot preparation120110
Total875700

Assignment Description and Requirement Analysis

This assignment requires a calculator system based on a front-end and back-end separation architecture. The front end is responsible for user input, button interaction, result display, and history display. The back end is responsible for expression validation, expression parsing, calculation, exception handling, and database operations. The two parts communicate through HTTP JSON APIs.

I reused the visual identity of my previous xxr Calculator, including its star-character theme, and refactored the required core features into a separated architecture. The browser sends the original expression to the server. The server calculates the result, stores the expression, result, and creation time in SQLite, and returns a JSON response. Therefore, the browser cannot generate a new valid calculation result when the back-end service is unavailable.

The required functions implemented in this project are:

  1. Addition, subtraction, multiplication, and division.
  2. Compound expressions with operator precedence, parentheses, decimal numbers, and unary plus or minus.
  3. Error feedback for invalid expressions and division by zero.
  4. Persistent calculation history in a back-end SQLite database.
  5. History retrieval from the back end.
  6. Deletion of one selected history record by ID.

The star-character theme is an interface enhancement inherited from xxr Calculator. It improves recognition and does not replace the required back-end implementation.

Finished Product and Test Evidence

Front-end deployment URL: https://2310209788-del.github.io/xxr-calculator-frontend/

Back-end deployment URL: https://shixunguo.pythonanywhere.com/api/history

The following screenshots must be captured from the final deployed version. Upload each image through the CSDN editor, replace IMAGE_URL with the inserted image URL, and retain the caption in the alt text. This set provides 12 pieces of evidence, exceeding the assignment minimum of 10.

Test Cases and Results

Test IDInput or OperationExpected ResultActual Result
T0112 + 820Passed
T021 + 2 * 37Passed
T03(1 + 2) * 39Passed
T04-5 + 83Passed
T0510 / 42.5Passed
T061 / 0A division-by-zero error messagePassed
T071 +An invalid-expression error messagePassed
T08Refresh the history pageRecords are loaded from the back-end databasePassed
T09Delete one selected recordOnly the selected record is deletedPassed

Problems and Solutions

The first challenge was ensuring that the browser did not calculate the final result. I solved this by sending the original expression to POST /api/calculate and displaying only the JSON result returned by the server.

The second challenge was evaluating expressions safely. Instead of using eval, the back end uses a recursive-descent parser. This supports operator precedence, parentheses, decimal numbers, unary signs, and error handling without executing user input as code.

The third challenge was deployment. The front end was deployed on GitHub Pages, while the Python API was deployed on PythonAnywhere with a WSGI entry point. Cross-origin requests are supported through CORS response headers.

Figure 1 — Home page

img

Figure 2 — Addition

img

Figure 3 — Subtraction

img

Figure 4 — Multiplication

img

Figure 5 — Unary sign

img

Figure 6 — Operator precedence

img

Figure 7 — Parentheses

img

Figure 8 — Decimal division

img

Figure 9 — Division-by-zero validation

img

Figure 10 — Invalid-expression validation

img

Figure 11 — Database-backed history

img

Figure 12 — Delete a specified history record

img

Figure 13 — Persistence after restart

img

Figure 14 — HTTP JSON evidence

img

The browser accesses:

https://shixunguo.pythonanywhere.com/

Figure 14 is particularly important: it directly supports the claim that the browser requests a server-side calculation instead of calculating the final result itself.

Design and Implementation Process

Overall Architecture

xxr Calculator Front End
  ├─ Expression input and button interaction
  ├─ fetch requests and result display
  └─ History page
          │ HTTP / JSON
          ▼
Python Back-End API
  ├─ Input validation
  ├─ Recursive-descent expression parser
  ├─ Error handling
  └─ SQLite read and write operations
          │
          ▼
calculation_history table

Functional Structure

xxr Calculator
├─ Basic Calculation
│  ├─ Expression Input
│  ├─ Server-Side Calculation
│  ├─ Operator Precedence and Parentheses
│  └─ Error Messages
├─ Calculation History
│  ├─ Database Persistence
│  ├─ History Query
│  └─ Delete One Record
└─ Star-Character Theme

Front-End Design

The front end consists of index.html, style.css, and app.js. It does not evaluate mathematical expressions locally. When the user presses the equals button, the browser sends the original expression to the API. It only displays the result returned by the server.

The request function centralizes HTTP requests and handles network failures, invalid JSON, and server-side error responses. The history page loads data from the back end rather than browser cache or localStorage.

Back-End and API Design

MethodPathRequest or ResponseResponsibility
POST/api/calculate{ "expression": "(1+2)*3" }Calculate and save a history record
GET/api/historyReturns an items arrayRetrieve the latest 200 records
DELETE/api/history/{id}204 No ContentDelete one record by ID

Successful calculation response:

{
  "success": true,
  "id": 12,
  "expression": "(1+2)*3",
  "result": "9",
  "createdAt": "2026-10-01T10:20:00+08:00"
}

Invalid input response:

{
  "success": false,
  "message": "Division by zero is not allowed"
}

Database Design

The SQLite table is named calculation_history.

FieldTypeDescription
idINTEGERAuto-increment primary key used for deleting one record
expressionTEXTThe original expression entered by the user
resultTEXTThe result calculated by the back end
created_atTEXTCreation time in ISO 8601 format

The database file is initialized automatically when the back end starts for the first time. The database file is excluded from Git because it contains local test data, not source code.

Expression Parsing and Error Handling

The back end does not use eval, exec, or any mechanism that executes user input as code. Instead, it uses a recursive-descent parser. The parser separates the grammar into three levels:

  • sum handles addition and subtraction.
  • product handles multiplication and division, so it has higher precedence than addition and subtraction.
  • primary handles numbers, parentheses, and unary plus or minus.

The parser accepts only numbers, + - * /, parentheses, decimal points, and scientific notation. It rejects unsupported characters. It also returns an HTTP 400 response for division by zero, mismatched parentheses, incomplete expressions, and non-finite results.

Front-End and Back-End Interaction Flow

  1. The user enters (1+2)*3 and presses the equals button.
  2. The front end sends POST /api/calculate.
  3. The back end validates and parses the expression, then calculates 9.
  4. The back end inserts the expression, result, and time into SQLite.
  5. The back end returns a JSON response.
  6. The front end displays the returned result and refreshes the recent history area.
  7. The history page uses GET /api/history. Deleting a record uses DELETE /api/history/{id}, followed by a new history request.

Deployment Instructions

The front end is deployed with GitHub Pages from the main branch and the repository root. Its public URL is https://2310209788-del.github.io/xxr-calculator-frontend/.

The back end is deployed on PythonAnywhere. The project was cloned with the following command in a Bash console:

git clone https://github.com/2310209788-del/xxr-calculator-backend.git

The PythonAnywhere WSGI configuration imports application from wsgi.py, and the service is reloaded after each code update. Its history API is publicly available at https://shixunguo.pythonanywhere.com/api/history.

The front-end config.js sets window.XXR_API_BASE_URL to https://shixunguo.pythonanywhere.com, so all calculations and history requests use the public back-end API.

Key Code Explanation

The Front End Sends the Expression

const data = await request('/api/calculate', {
  method: 'POST',
  body: JSON.stringify({ expression: original }),
});
expression = data.result;

The front end sends original, which is the expression entered by the user, rather than a locally calculated result. It updates the display only with data.result returned by the back end.

Safe Server-Side Parsing

result = format_number(ExpressionParser(expression).parse())

ExpressionParser processes the expression according to the defined grammar instead of sending the string to the Python interpreter. This design satisfies both the precedence requirement and the security requirement.

Parameterized Database Insertion

connection.execute(
    "INSERT INTO calculation_history(expression, result, created_at) VALUES (?, ?, ?)",
    (expression, result, created_at),
)

Parameterized SQL prevents user input from being concatenated into SQL statements directly.

Deleting One History Record

cursor = connection.execute(
    "DELETE FROM calculation_history WHERE id = ?", (history_id,)
)

The front end sends the selected record ID. The back end deletes the database row and the front end reloads the current history list. Therefore, the displayed state always follows the database state.

Personal Journey and Learnings

This assignment helped me understand that front-end and back-end separation is more than placing browser code and server code in different folders. The business boundary must also be clear: the front end manages interaction, while the back end performs trusted calculation and stores persistent data. If the browser calculates a result before sending it to the server, the project does not satisfy the core requirement of this assignment.

The most important technical challenge was safe expression parsing. I chose a recursive-descent parser instead of eval, so the system can handle precedence, parentheses, unary signs, and division-by-zero errors without executing arbitrary user input. I also learned the difference between browser storage and database persistence. localStorage may be useful for user interface preferences, but it cannot replace a back-end database for calculation history.

In the future, I plan to migrate the unit conversion, BMI calculation, base conversion, and exchange-rate functions from the original xxr Calculator into back-end APIs. I would also add pagination, search, and individual user histories while keeping the same separation between presentation and core business logic.

...全文
55 回复 打赏 收藏 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
内容概要:本文研究了基于深度强化学习的多无人机辅助边缘计算网络路径规划方法,旨在通过深度强化学习算法优化多无人机在执行任务时的飞行路径,以提高边缘计算网络的服务质量和效率。文中系统阐述了深度强化学习的基本原理及其在无人机路径规划中的应用,重点解决了动态环境适应性和多目标优化等关键技术难题。研究提出了一种高效的算法框架,能够有效应对复杂环境中的障碍物规避、能耗最小化和任务完成时间最短化等多重挑战。该框架通过Matlab代码实现,并经过大量仿真实验验证,结果表明,相较于传统路径规划方法,所提方法在确保飞行安全的前提下,显著提升了无人机的任务执行效率和网络服务质量,展现了优异的性能表现和广阔的应用前景。; 适合人群:具备一定编程基础,特别是熟悉Matlab编程语言,对无人机技术、边缘计算或深度强化学习感兴趣的科研人员和技术开发者。; 使用场景及目标:①为研究人员提供一种新的无人机路径规划解决方案,特别是在复杂动态环境下;②促进深度强化学习技术在无人机辅助边缘计算网络中的应用和发展;③为相关领域的工程技术人员提供技术支持和参考案例。; 阅读建议:读者在阅读本文时,应重点关注深度强化学习算法的设计思路及其在无人机路径规划中的具体应用,同时结合提供的Matlab代码进行实践操作,以便更好地理解和掌握该技术的核心要点。
已经博主授权,源码转载自 https://pan.quark.cn/s/a4b39357ea24 卷积神经网络(CNN,Convolutional Neural Network)属于一种深度学习模型类别,它对于处理具有规则网格状结构的数据类型表现尤为出色,尤其是图像数据。在手写体识别这一具体任务中,CNN能够高效地识别图像中的关键特征,例如笔画的几何形态、走向以及相互连接的模式,进而精确地识别出特定的手写字符。本项目的实现依托于TensorFlow框架,这是一个由Google研发的开源机器学习平台,其提供了大量便捷的工具和应用程序接口(API),用于构建和训练结构复杂的神经网络模型。 我们需要深入掌握卷积神经网络的基本构造。CNN通常由多个核心组件构成,包括卷积层(Convolutional Layer)、池化层(Pooling Layer)、全连接层(Fully Connected Layer)以及非线性激活函数(例如ReLU)。卷积层借助滤波器(Filter)在输入图像上执行扫描操作,负责特征的提取工作;池化层则通过降低数据的空间维度来提升计算效率;全连接层将提取出的特征与输出类别进行关联映射,最后采用Softmax函数完成最终的分类任务。 在这个手写字符识别的项目实践中,初始阶段可能进行了数据预处理步骤,涉及读取特定的二进制文件(比如train-labels.idx1-ubyte、t10k-labels.idx1-ubyte、train-images.idx3-ubyte、t10k-images.idx3-ubyte),这些文件可能存储了MNIST数据集中的手写数字图像及其对应的类别标签。MNIST数据集作为机器学习领域广泛应用的标准化基准,包含了60,000个训练...

91

社区成员

发帖
与我相关
我的任务
社区描述
梅努斯-软件工程
软件工程 高校 福建省·福州市
社区管理员
  • FZU_SE_LQF
  • zjcTander
  • 木村修
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧