Web calculator based on flask framework

Course for This Assignmenthttps://bbs.csdn.net/forums/ssynkqtd-04
Assignment Requirementshttps://bbs.csdn.net/topics/617378696
MU STU ID and FZU STU ID

21125147_832101222                                                           

Objectives of This Assignmentimprove the functions of the previous calculator

github

frontend : GitHub - localflvcko/frontend

backend : localflvcko/backend (github.com)

目录

psp form

calculator display

Design 

Code explantion 

1.frontend

2.backend

Personal Journey and Learnings

psp form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning3030
• Estimate55
Development3030
• Analysis15100
• Design Spec3050
• Design Review3050
• Coding Standard3050
• Design15020
• Coding10050
• Code Review5030
• Test5030
Reporting3030
• Test Report5050
• Size Measurement5050
• Postmortem & Process Improvement Plan100100
Sum930900

calculator display

20231022_140015

databases

20231022_140134

Design 

Front-end design:

1. User interface: Create a user interface, usually defined using HTML. This user interface should include input fields for entering numbers, buttons for selecting operations (e.g., adding, subtracting), and a result display area.

2. user input: Using HTML form elements or input boxes, users can enter numbers. These input fields should have unique IDs so that JavaScript can access and process the user input.

3. JavaScript: Use JavaScript to process user input and communicate with the backend. For example, when the user clicks on the add button, JavaScript should capture the value of the input field, package the data into JSON format, and then send the data to a specific route on the backend using AJAX or Fetch API.

4. Result Display: In the user interface, JavaScript is used to receive the calculation results from the backend and display the results on the page.

Backend Design (Flask):

1. Flask Application Create a Flask application to handle front-end requests and perform calculations. You can use the Flask framework to easily create routes and handle HTTP requests.

2. Route Definition: Define routes in your Flask application to handle different operations. For example, you can define a route to handle the sum operation and another to handle the subtract operation. These routes should receive data from the front-end, perform calculations, and then return the results to the front-end.

3. Database Connectivity: If you need to store the results of your calculations to a MySQL database, you will need to add database connectivity code to your Flask application. This may include connecting to a MySQL database server and inserting the results into a database table after the calculation.

4. JSON Response: In Flask routing, the results of the calculation should be returned to the front-end in JSON format. This can be accomplished through Flask's `jsonify` function, which ensures that the front-end can easily parse and display the results.

Overall, front-end design needs to focus on the user interface and interaction with the user, while back-end design needs to handle the computational logic and interaction with the database. Communication between the front-end and back-end usually uses the JSON format. This design idea will help you build a calculator application with front-end and back-end connections.

Code explantion 

1.frontend

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>计算器</title>
    <link rel="stylesheet" href="cal.css">
</head>
<body>
    <!-- Calculator Container -->
    <div class="calculator">
        <input class="show" id="show" placeholder="0">
    </div>

    <main class="flex">
        <!-- Left Panel: Buttons for Operations and Functions -->
        <aside class="flex">
            <div class="top flex">
                <input class="button" type="button" value="CE">
                <input class="button" type="button" value="C">
                <button class="button" onclick="display('(')">(</button>
                <button class="button" onclick="display(')')">)</button>
                <input class="button" type="button" value="sqrt">
                <input class="button" type="button" value="log">
                <button class="button" onclick="switchToDeg()">deg">
                <input class="button" type="button" value="x!">
            </div>
            <div class="num flex">
                <input class="button" type="button" value="sin">
                <input class="button" type="button" value="7">
                <input class="button" type="button" value="8">
                <input class="button" type="button" value="9">
                <input class="button" type="button" value="cos">
                <input class="button" type="button" value="4">
                <input class="button" type="button" value="5">
                <input class="button" type="button" value="6">
                <input class="button" type="button" value="tan">
                <input class="button" type="button" value="1">
                <input class="button" type="button" value="2">
                <input class="button" type="button" value="3">
                <button class="button" onclick="switchToRad()">rad">
                <input class="button" type="button" value="0">
                <input class="button" type="button" value=".">
                <input class="button" type="button" value="ans">
            </div>
        </aside>

        <!-- Right Panel: Arithmetic and Equals Buttons -->
        <aside class="flex">
            <input class="button" type="button" value="%">
            <input class="button" type="button" value="/">
            <input class="button" type="button" value="*">
            <input class="button" type="button" value="-">
            <input class="button" type="button" value="+">
            <input class="button" type="button" value="=">
        </aside>
    </main>
    <script src="cal.js"></script>
</body>
</html>
var historyData = []; // 存放历史记录
var results = []; // 用于存放结果与历史数据拼接的记录

function append_number(num) {
    // 追加数字到显示框
    document.form.show.value += num;
    return document.form.show.value;
}

function append_operator(op) {
    var text = document.form.show.value;
    var length = text.length;

    // 如果最后一个字符不是数字,则删除最后一个字符
    if (text[length - 1] < '0' || text[length] > '9') {
        document.form.show.value = text.substring(0, length - 1);
    }

    // 追加运算符到显示框
    document.form.show.value += op;
}

function display_special(op) {
    var text = document.form.show.value;
    text += op;
    document.form.show.value = text;
}

function perform_calculation() {
    try {
        var expression = document.form.show.value;

        if (expression) {
            document.form.show.value = eval(expression);

            // 处理除以零的情况
            if (eval(expression) === Infinity) {
                document.form.show.value = "error";
            }

            var result = eval(expression);

            // 发送历史记录到服务器
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://127.0.0.1:5000/get_history', true);
            xhr.setRequestHeader('Content-type', 'application/json');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log(xhr.responseText);
                }
            };
            const data = {
                expression: expression,
                result: result
            };
            xhr.send(JSON.stringify(data));
        }
    } catch {
        document.form.show.value = "error";
    }
}

function clear_display() {
    // 清空显示框
    document.form.show.value = "";
}

function calculate_sin() {
    perform_calculation();
    var angle = document.form.show.value;
    var sinValue = Math.sin(angle / 180 * Math.PI);
    sinValue = sinValue.toFixed(2);
    clear_display();
    document.form.show.value += sinValue;
}

function calculate_cos() {
    perform_calculation();
    var angle = document.form.show.value;
    var cosValue = Math.cos(angle / 180 * Math.PI);
    cosValue = cosValue.toFixed(2);
    clear_display();
    document.form.show.value += cosValue;
}

function calculate_tan() {
    perform_calculation();
    var angle = document.form.show.value;
    var tanValue = Math.tan(angle / 180 * Math.PI);
    tanValue = tanValue.toFixed(2);
    clear_display();
    document.form.show.value += tanValue;
}

function calculate_ln() {
    perform_calculation();
    document.form.show.value = Math.log10(document.form.show.value);
}

function remove_last_character() {
    // 删除最后一个字符
    var text = document.form.show.value;
    var length = text.length;
    document.form.show.value = text.substring(0, length - 1);
}

function calculate_sqrt() {
    perform_calculation();
    document.form.show.value = Math.sqrt(document.form.show.value);
}

function calculate_factorial(n) {
    let result = 1;
    for (let i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

function calculate_factorial_and_display() {
    perform_calculation();
    document.form.show.value = calculate_factorial(document.form.show.value);
}

function handle_operation(str) {
    if (str >= '0' && str <= '9') {
        append_number(str);
    }
    if (str === '+' || str === '*' || str === '/' || str === '-' || str === '.' || str === '%') {
        append_operator(str);
    }
    if (str === 'sin') {
        calculate_sin();
    }
    if (str === 'cos') {
        calculate_cos();
    }
    if (str === 'tan') {
        calculate_tan();
    }
    if (str === 'ln') {
        calculate_ln();
    }
    if (str === 'x!') {
        calculate_factorial_and_display();
    }
    if (str === '=') {
        perform_calculation();
    }
    if (str === 'AC') {
        clear_display();
    }
    if (str === 'sqrt') {
        calculate_sqrt();
    }
    if (str === 'BACK') {
        remove_last_character();
    }
    return document.form.show.value;
}

function fetch_history() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://127.0.0.1:5000/get_calculation', true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                data = JSON.parse(xhr.responseText);
                records = data['data'];
                let historyText = "";
                for (let i = 0; i < records.length; i++) {
                    historyText += records[i][0] + " = " + records[i][1] + "\n";
                }
                document.form.show.value = historyText;
            }
        }
    };
    xhr.send();
}
.calculator {
    height: 80px;
    width: 250px;
    background-color: #3498db; /* 蓝色背景 */
}

#dots {
    display: flex;
}

.button {
    height: 50px;
    width: 50px;
    color: #fff; /* 白色字体 */
    font-size: large;
}

.show {
    display: flex;
    flex-direction: row-reverse;
    height: 50px;
    width: 242px;
    font-size: 2em;
    color: #e74c3c; /* 红色字体 */
    margin-top: 7px;
    margin-right: 2px;
}

.form {
    color: #f1c40f; /* 黄色字体 */
}

.flex {
    display: flex;
}

.dot {
    height: 13px;
    width: 13px;
    border-radius: 50%;
    margin-left: 5px;
    margin-top: 5px;
}

#top .button {
    background-color: #27ae60; /* 绿色按钮背景 */
}

#num .button {
    background-color: #8e44ad; /* 紫色按钮背景 */
}

aside-right .button {
    background-color: #f39c12; /* 橙色按钮背景 */
}

main {
    width: 250px;
    height: 300px;
    flex-wrap: wrap;
}

#num {
    flex-wrap: wrap;
}

#top {
    flex-wrap: wrap;
}

aside-right {
    flex-direction: column;
}

aside-left {
    width: 200px;
    flex-direction: row;
    flex-wrap: wrap;
}

2.backend

from flask import Flask, request, jsonify
from flask_cors import CORS
import pymysql
import datetime

db_connection = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123456',
    database='calculator'
)

app = Flask(__name__)
CORS(app)
db_cursor = db_connection.cursor()

@app.route('/record_history', methods=['POST'])
def record_history():
    data = request.get_json()
    expression = data.get('expression')
    result = data.get('result')

    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    data_tuple = (current_time, expression, result)
    insert_query = "INSERT INTO alan_calculate VALUES (%s, %s, %s)"
    db_cursor.execute(insert_query, data_tuple)
    db_connection.commit()

    response_message = "Recorded successfully"
    return jsonify({"message": response_message})

@app.route('/fetch_calculations', methods=['GET'])
def fetch_calculations():
    db_cursor.execute("SELECT expression, result FROM alan_calculate ORDER BY time DESC LIMIT 10")
    data = db_cursor.fetchall()
    return jsonify({"data": data})

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

Personal Journey and Learnings

1. Technical challenges:

In this project, I faced both front-end and back-end technical challenges. The front-end part involved HTML, CSS, and JavaScript, and I needed to create an intuitive user interface and make sure that the data was passed correctly to the back-end. The backend used the Flask framework, which was a new learning opportunity for me, but also provided me with a powerful tool to handle HTTP requests and database connections.

2. database integration:

Integration with MySQL database was an important aspect. I learned how to establish database connections, create tables to store calculations, and write SQL queries to insert and retrieve data. This gave me a better understanding of how databases work.

3. front-end and back-end communication:

Understanding how to implement front-end and back-end communication is key. I learned how to pass data using the JSON format and how to send data to the backend using JavaScript's Fetch API. This also opened the door to web development, allowing me to build more complex applications.

4. Continuous learning:

After this project, I learned that in technology, learning never ends. New technologies and tools emerge every day, so it is important to stay sensitive to new knowledge. I plan to continue learning and improving my skills.

Overall, this calculator project was a major milestone in my technical growth. Not only did I acquire front-end and back-end development skills, but I also learned how to face challenges, solve problems, and continue to improve myself. This experience was not only a project, but also a journey full of lessons and accomplishments that will continue to shape my career. I look forward to future projects and continuing to explore and learn.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用Flask框架实现一个Web计算器可以按照以下步骤进行: 1. 首先,导入Flask模块和相关依赖库: ```python from flask import Flask, render_template, request ``` 2. 创建一个Flask应用: ```python app = Flask(__name__) ``` 3. 定义一个路由和对应的视图函数来处理GET和POST请求: ```python @app.route('/', methods=['GET', 'POST']) def calculator(): if request.method == 'POST': # 处理计算逻辑 pass return render_template('calculator.html') ``` 4. 创建一个calculator.html模板文件,用于显示计算器界面和接收用户输入。在模板中添加一个表单,以便用户输入计算表达式: ```html <form action="" method="post"> <input type="text" name="expression" placeholder="请输入计算表达式" required> <input type="submit" value="计算"> </form> ``` 5. 在视图函数中处理用户提交的计算表达式,并返回计算结果: ```python @app.route('/', methods=['GET', 'POST']) def calculator(): if request.method == 'POST': expression = request.form.get('expression') result = eval(expression) # 使用eval函数计算表达式结果 return render_template('calculator.html', result=result) return render_template('calculator.html') ``` 6. 修改calculator.html模板文件,以便显示计算结果: ```html <h3>计算结果:{{ result }}</h3> ``` 7. 在main函数中运行Flask应用: ```python if __name__ == '__main__': app.run() ``` 通过以上步骤,我们就可以使用Flask框架实现一个简单的Web计算器。用户可以通过浏览器访问应用的首页,输入计算表达式并提交,然后应用将计算表达式的结果返回并显示在页面上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值