102102144郑荣城软工第二次作业----前后端分离计算器

本文详细描述了一个计算器项目的开发过程,包括基本功能展示、代码结构(Python后端与JavaScript前端的交互)、心路历程和技术选择。作者通过该项目实践加深了对Flask和前端技术的理解,并强调了学习与改进的重要性。
摘要由CSDN通过智能技术生成

@102102144郑荣城实践2

项目描述链接
课程名称2301-计算机学院-软件工程课程链接
作业要求完成一个前后端交互计算器作业链接
作业目标掌握基础前后端开发
计算器的基础页面展示

在这里插入图片描述

Git仓库链接和代码
项目链接
个人仓库仓库链接
全部代码代码链接
PSP表格
PSPPersonal Software Process Stages预估耗时 (分钟)实际耗时 (分钟)
Planning计划2020
Estimate估计这个任务需要多少时间1515
Analysis需求分析(包括学习新技术)300320
Development开发600780
Design spec生成设计文档3030
Coding standard代码规范2020
Design具体设计300380
Coding具体编码240300
Code review代码复审120140
Test测试(自我测试,修改代码、提交修改)6050
Reporting报告2025
Size measurement计算工作量1010
Total合计9901185

一、基本功能展示

-说明:本计算器实现了加减乘除幂运算,回退清除以及科学计算器的部分三角函数功能,对于本地使用记录存储和利息运算还有待开发

二、代码结构

代码功能
  • Python

  • Python 用于后端逻辑处理,计算表达式的值,使用 Flask 框架快速开发和部署,并与前端实现交互,在该部分还实现了一些科学计算器的功能

  • Js

  • JavaScript 被用于处理用户交互和动态内容。它监听按钮点击事件,更新表达式,向 Flask API 发送请求来获取计算结果,并动态更新历史记录,用以交互

  • Html

  • HTML 主要用于布局和元素的定义,使用了按钮、输入框和其他元素来构建用户界面,在编写代码的同时把属于css的内容也添加到该部分,用于样式化 HTML 元素,包括布局、颜色、字体等

  • 总结

  • 该网页计算器项目是一个完整的前后端应用,前端使用 HTML/CSS/JavaScript 构建,后端使用 Python 和 Flask。用户在前端输入数学表达式,前端将这些信息发送到后端,后端处理这些信息并返回结果,前端再将结果展示给用户

代码展示
  • 全部代码展示
  • Python
from flask import Flask, request, jsonify
from flask_cors import CORS
import math
import re

app = Flask(__name__)
CORS(app)


@app.route('/calculate', methods=['POST'])
def calculate():
    try:
        data = request.json
        expression = data['expression']

        # 使用正则表达式替换 sin, cos, tan 函数
        expression = re.sub(r'sin\((.*?)\)', lambda x: str(math.sin(eval(x.group(1)))), expression)
        expression = re.sub(r'cos\((.*?)\)', lambda x: str(math.cos(eval(x.group(1)))), expression)
        expression = re.sub(r'tan\((.*?)\)', lambda x: str(math.tan(eval(x.group(1)))), expression)

        result = eval(expression)
        return jsonify({'result': result})
    except Exception as e:
        print(e)  # 记录错误
        return jsonify({'error': '表达式无效'}), 400


if __name__ == "__main__":
    app.run(debug=True)
  • Js
let display = document.getElementById('display');

function appendToDisplay(value) {
    display.value += value;
}

function clearDisplay() {
    display.value = '';
}

function calculate() {
    fetch('/calculate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            expression: display.value
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
        } else {
            display.value = data.result;
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
}
  • Html
<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线计算器</title>
    <style>
        #calculator {
            max-width: 400px; /* 修改为 400px 宽以更好地容纳新按钮 */
            margin: auto;
        }

        #display {
            width: calc(100% - 62px);
            height: 50px;
            padding: 10px;
            margin-bottom: 10px;
            font-size: 24px;

        }

        #buttons button {
            width: calc(25% - 10px);
            height: 70px;
            font-size: 24px;
            margin: 5px 0;
            float: left;
            background-color:antiquewhite;
        }

        #buttons:after {
            content: "";
            display: table;
            clear: both;
        }
    </style>
</head>

<body>

    <div id="calculator">
        <input type="text" id="display" style="background-color:lavender"  disabled>
        <div id="buttons">
            <button onclick="appendToDisplay('(')">(</button>
            <button onclick="appendToDisplay(')')">)</button>
            <button onclick="deleteLast()"></button>
            <button onclick="clearDisplay()">C</button>
            <button onclick="appendToDisplay('sin(')">sin</button>
            <button onclick="appendToDisplay('cos(')">cos</button>
            <button onclick="appendToDisplay('tan(')">tan</button>
            <button onclick="appendToDisplay('**')">^</button>
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('+')">+</button>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('-')">-</button>
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('*')">*</button>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="calculate()">=</button>
            <button onclick="appendToDisplay('/')">/</button>
        </div>
    </div>

    <script>
        let display = document.getElementById('display');

        function appendToDisplay(value) {
            display.value += value;
        }

        function clearDisplay() {
            display.value = '';
        }

        function deleteLast() {
            display.value = display.value.slice(0, -1);
        }

        function calculate() {
            fetch('http://localhost:5000/calculate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    expression: display.value
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                } else {
                    display.value = data.result;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误');
            });
        }
    </script>
</body>

</html>

三. 心路历程及思考总结

确定结构
  • 后端原本想选择spring boot,最后选择 Flask 作为后端技术,因为简单易用,适合快速原型开发,并选用HTML+CSS+JS的组合快速构建前端
前端开发
  • 在前端花了比较多心思,学习了html编辑等,用标准的 HTML 元素和结构设计了用户界面以及所需要的功能按键
后端开发
  • 后端的开发并没有很深入,实现交互的同时加入一些三角函数功能,还可以进一步改进
收获
  • 这个项目让我加深了对 Flask 和前端技术的理解,这是第一次设计前后端分离的小项目,让我有了不错的体验,本次作业不仅让我加深了对前端技术的理解,也让我意识到持续学习和改进程序的重要性。每个问题对我而言都是一个学习和成长的机会。我将继续探索、学习,以成为一名更优秀的开发者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值