A calculator with front and rear ends separated


I. Introduction

  • This visual calculator is an improvement over the previous version. It includes basic calculator functions as well as advanced calculator features such as square root, trigonometric functions, logarithms, and parentheses calculations. Additionally, it has a feature to retrieve the calculation history.
  • In this calculator, the flask module from the web framework is used. The front-end is built using HTML to create the web interface, while the back-end uses Python code to inspect the webpage and perform the calculations.
  • Link to the project code: https://github.com/Kanomace/EE308FZ_SE_A2

II. Basic Information

The link of my classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617378696
The Aim of This AssignmentCreate a calculator with a visual interface
MU STU ID and FZU STU ID21126356_832101325

III. PSP Table

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning4060
• Estimate4060
Development420460
• Analysis5060
• Design Spec1520
• Design Review2530
• Coding Standard1015
• Design5065
• Coding230220
• Code Review2025
• Test2025
Reporting70100
• Test Repor4070
• Size Measurement2015
• Postmortem & Process Improvement Plan1015
Sum520620

VI. Design and Implementation Process

Front-End Development

  • HTML: Create a user interface with numbers and buttons, along with a display panel to show input and output, as well as a history record interface. Transfer user input to the backend program.
  • JavaScript: Use the $.ajax function in the jQuery library to make asynchronous HTTP requests. Communicate with the server through asynchronous requests to send compute requests and get history. After the calculation results are successfully obtained, the results are displayed on the page and the history list is updated.

Back-End Development

  • python: A back-end application based on Flask framework is implemented, which provides the function of calculator and history management. By defining routing handlers, applications can handle HTTPrequests from the front end. For calculator functions, applications handle mathematical operations and function calls by accepting expressions in POSTrequests and evaluating them using the eval()function. The results are returned to the front-end in JSON format and stored in the history file. For history management, the application provides an interface for GET requests to get the history stored in the file.
    在这里插入图片描述

V. Front-end Code

<!DOCTYPE html>
<html>
<head>
    <title>Calculator</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h1>Calculator</h1>
    <input type="text" id="expression" placeholder="Enter an expression">
    <br>
    <table>
        <tr>
            <td><button onclick="appendCharacter('7')">7</button></td>
            <td><button onclick="appendCharacter('8')">8</button></td>
            <td><button onclick="appendCharacter('9')">9</button></td>
            <td><button onclick="appendCharacter('/')">/</button></td>
            <td><button onclick="appendCharacter('sin(')">sin</button></td>
            <td><button onclick="appendCharacter('cos(')">cos</button></td>
            <td><button onclick="appendCharacter('tan(')">tan</button></td>
        </tr>
        <tr>
            <td><button onclick="appendCharacter('4')">4</button></td>
            <td><button onclick="appendCharacter('5')">5</button></td>
            <td><button onclick="appendCharacter('6')">6</button></td>
            <td><button onclick="appendCharacter('*')">*</button></td>
            <td><button onclick="appendCharacter('asin(')">asin</button></td>
            <td><button onclick="appendCharacter('acos(')">acos</button></td>
            <td><button onclick="appendCharacter('atan(')">atan</button></td>
        </tr>
        <tr>
            <td><button onclick="appendCharacter('1')">1</button></td>
            <td><button onclick="appendCharacter('2')">2</button></td>
            <td><button onclick="appendCharacter('3')">3</button></td>
            <td><button onclick="appendCharacter('-')">-</button></td>
            <td><button onclick="appendCharacter('sqrt(')">sqrt</button></td>
            <td><button onclick="appendCharacter('exp(')">exp</button></td>
            <td><button onclick="appendCharacter('^')">^</button></td>
        </tr>
        <tr>
            <td><button onclick="appendCharacter('0')">0</button></td>
            <td><button onclick="appendCharacter('.')">.</button></td>
            <td><button onclick="appendCharacter('(')">(</button></td>
            <td><button onclick="appendCharacter(')')">)</button></td>
            <td><button onclick="appendCharacter('log(')">log</button></td>
            <td colspan="2"><button onclick="clearExpression()">Clear</button></td>
        </tr>
        <tr>
            <td colspan="2"><button onclick="appendCharacter('+')">+</button></td>
            <td colspan="2"><button onclick="appendCharacter('pi')">π</button></td>
            <td colspan="3"><button onclick="calculate()">Calculate</button></td>
        </tr>
    </table>
    <br>
    <p id="result"></p>
    <h2>History</h2>
    <ul id="history"></ul>

    <script>
        function appendCharacter(character) {
            var expression = document.getElementById("expression");
            expression.value += character;
            expression.focus();
        }

        function clearExpression() {
            document.getElementById("expression").value = "";
        }

        function calculate() {
            var expression = document.getElementById("expression").value;
            $.ajax({
                type: "POST",
                url: "/calculate",
                data: JSON.stringify({ expression: expression }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    document.getElementById("result").innerHTML = "Result: " + response.result;
                    document.getElementById("expression").value = "";
                    getHistory();
                }
            });
        }

        function getHistory() {
            $.ajax({
                type: "GET",
                url: "/history",
                success: function (response) {
                    var historyList = document.getElementById("history");
                    historyList.innerHTML = "";
                    for (var i = 0; i < response.length; i++) {
                        var item = document.createElement("li");
                        item.appendChild(document.createTextNode(response[i]));
                        historyList.appendChild(item);
                    }
                }
            });
        }
    </script>
</body>
</html>

VI. Back-end Code Description

1. Import the necessary modules:

  • First, the Flask framework and other required modules are imported. Flask is used to create Web applications, request is used to process HTTP requests, jsonify is used to process JSON data, render_template is used to render HTML templates, and math is Python’s math library.
from flask import Flask, request, jsonify, render_template
import math

2. Create a Flask application instance and variable to the file path where the history will be stored:

app = Flask(__name__)
history_file = "history.txt"

3. Define functions to save the calculation history to a file and loads the history from the file and returns a list.

def save_history(entry):
    with open(history_file, 'a') as file:
        file.write(entry + '\n')

def load_history():
    history = []
    with open(history_file, 'r') as file:
        for line in file:
            history.append(line.rstrip('\n'))
    return history

4. Define a route using the @app.route(‘/’) decorator, handle the request for the root path, and return the rendered index.html template:

  • Define a route using the @app.route(‘/calculate’, methods=[‘POST’]) decorator to handle compute requests. Get the expression from the POST request and try to evaluate the result using the eval() function. If the evaluation is successful, the expression and result are saved to the history and the result is returned in JSON format. If the evaluation fails, the eval() function and math.dict are used to evaluate the result, ignoring the built-in function, and the expression and result are saved to the history and returned in JSON format.
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/calculate', methods=['POST'])
def calculate():
    expression = request.get_json()['expression']
    try:
        result = eval(expression)
        entry = f"Expression: {expression}, Result: {result}"
        save_history(entry)
        return jsonify({"result": result})
    except Exception as e:
        result = eval(expression, {'__builtins__': None}, math.__dict__)
        entry = f"Expression: {expression}, Result: {result}"
        save_history(entry)
        return jsonify({'result': result})
@app.route('/history', methods=['GET'])

def get_history():
    history = load_history()
    return jsonify(history)\
    
if __name__ == '__main__':
    app.run()

6. Complete code:

from flask import Flask, request, jsonify, render_template
import math

app = Flask(__name__)

history_file = "history.txt"

def save_history(entry):
    with open(history_file, 'a') as file:
        file.write(entry + '\n')

def load_history():
    history = []
    with open(history_file, 'r') as file:
        for line in file:
            history.append(line.rstrip('\n'))
    return history

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/calculate', methods=['POST'])
def calculate():
    expression = request.get_json()['expression']
    try:
        result = eval(expression)
        entry = f"Expression: {expression}, Result: {result}"
        save_history(entry)
        return jsonify({"result": result})
    except Exception as e:
        result = eval(expression, {'__builtins__': None}, math.__dict__)
        entry = f"Expression: {expression}, Result: {result}"
        save_history(entry)
        return jsonify({'result': result})

@app.route('/history', methods=['GET'])
def get_history():
    history = load_history()
    return jsonify(history)

if __name__ == '__main__':
    app.run()

VII. Presentation of the Finished Product

Basic operation

在这里插入图片描述

Scientific computer

请添加图片描述

Bracket calculation

在这里插入图片描述

VIII. Personal Journey and Learnings

  • Through this project, I have a clearer understanding of the front and back end interaction and services, and learn how to use the database and information interaction. During the development process, I gradually learned how to test the code I wrote. It also eliminates the use of html and JavaScript. When testing front-end pages, it is important to learn how to use browser developer pages.
  • In the future, I will learn more knowledge about the front and back end of sever, use the server to complete more software projects, and improve this visual calculator.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值