Assignment2-832102213_JIAYANG ZHANG

I.Introduction

This task is mainly to add functions to the calculator of job 1 to achieve more expanded functions, and store the input string and results in the back-end database, using the technology of back-end separation to complete this task. Based on the Html, Css and Javascript of job 1 as the front end, I will use flask framework in python library and Mysql database to complete data transmission and reading at the back end.

Link to the finished project code:

Front end: https://github.com/ThestarRYz/SE-EE301-Calculator-front-end

Back end: https://github.com/ThestarRYz/SE-EE301-Calculator-back-end

II.Personal Information

The link of my Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The link of requirement of this Assignmenthttps://bbs.csdn.net/forums/ssynkqtd-04
The Aim of this AssignmentWebsite Calculator
MU STU ID and FZU STU ID21126712_832102213

III. PSP Table

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning
• Estimate4040
Development
• Analysis4050
• Design Spec2025
• Design Review1515
• Coding Standard2020
• Design3030
• Coding130130
• Code Review4040
• Test3025
Reporting70100
• Test Repor2020
• Size Measurement2020
• Postmortem & Process Improvement Plan3030
Sum505545

IV.Thoughts before doing the project

Before doing this assignment, I first enriched the basic functions of the original front-end, realized more expanded functions, and slightly beautified the appearance of the design. About the back end, I went to the Internet to find a lot of knowledge about the back end and database, and learned that there are a lot of framework structures in the back end, and finally chose flask framework to learn the basic knowledge of this framework and the basic knowledge of MySQL database, and then studied how to link the front end, the back end framework and the database.

V.Design and implementation process

To clarify in advance, the functions that have been implemented and written in homework 1, the relevant code will not appear in this homework, I will show some code to expand the function and the front and back end, how to link the database, and the back end code.

See the GitHub link at the beginning for detailed code.

VI.Code description

Extended function: scientific calculator

Calculate radical symbols, trigonometric functions, logarithms, scientific notation.

function sqrt() {
    str = document.getElementById("text");
    var number = eval(str.value);
    result = Math.sqrt(number);
    str.value = result;
}

function log() {
    str = document.getElementById("text");
    var number = eval(str.value);
    result = Math.log10(number);
    str.value = result;
}

function exponential() {
    var str = document.getElementById("text").value;
    if (str === "") {
        document.getElementById("text").value = Math.E;
    } else {
        document.getElementById("text").value += Math.E;
    }
}

function pi() {
    var str = document.getElementById("text").value;
    if (str === "") {
        document.getElementById("text").value = Math.PI;
    } else {
        document.getElementById("text").value += Math.PI;
    }
}

function E() {
    var str = document.getElementById("text").value;
    var num = parseFloat(str);
    var result = num.toExponential();
    document.getElementById("text").value = result;
}

In homework 1, basic operations have been implemented, such as addition, subtraction, multiplication, division, and remainder. These are some ways to expand.(Note: The implementation of bracket calculation has been implemented in assignment 1.)

About the backend

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

app = Flask(__name__)
cors = CORS(app)

# MySQL数据库连接配置
db = pymysql.connect(
    host='localhost',
    user='root',
    password='1234567z',
    database='calculator_db'
)
cursor = db.cursor()

# 创建数据库表
def create_table():
    sql = """CREATE TABLE IF NOT EXISTS history (
                id INT AUTO_INCREMENT PRIMARY KEY,
                expression VARCHAR(255) NOT NULL,
                result DECIMAL(10,2) NOT NULL
            )"""
    cursor.execute(sql)
    db.commit()

# 插入历史记录
def insert_history(expression, result):
    sql = "INSERT INTO history (expression, result) VALUES (%s, %s)"
    cursor.execute(sql, (expression, result))
    db.commit()

# 获取历史记录
def get_history():
    sql = "SELECT * FROM history ORDER BY id DESC LIMIT 10"
    cursor.execute(sql)
    data = cursor.fetchall()
    return data

# 路由:获取历史记录API
@app.route('/api/calculator/history', methods=['GET'])
def get_history_api():
    data = get_history()
    history = [{'id': item[0], 'expression': item[1], 'result': float(item[2])} for item in data]
    return jsonify({
        "code": 200,
        "message": "ok",
        "data": {
            "history": history
            }
    })

@app.route('/api/calculator/history', methods=["POST"])
def store_result():
    expression = request.form.get("expression")
    result = request.form.get("result")
    print(expression, result)
    insert_history(expression, result)
    
    return jsonify({
        "code": 200,
        "message": "ok",
        "data": None
    })

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

This Python code is a Flask application that provides an API for a calculator history feature. It connects to a MySQL database to store and retrieve calculation history. Here’s an explanation of the code:

  1. Imports:

    • Flask: Imports the Flask framework for creating a web application.
    • jsonify: A helper function provided by Flask for returning JSON responses.
    • request: Allows access to HTTP request data.
    • pymysql: A Python MySQL client library for interacting with MySQL databases.
    • CORS: Cross-Origin Resource Sharing support for handling requests from different domains.
  2. Flask App Configuration:

    • app = Flask(__name__): Creates a Flask application instance.
  3. CORS Configuration:

    • cors = CORS(app): Initializes CORS support for handling cross-origin requests.
  4. Database Connection:

    • Establishes a connection to a MySQL database using pymysql.
  5. Database Cursor:

    • Creates a cursor object for executing SQL queries.
  6. Database Table Creation:

    • create_table(): Defines a function to create a table named history if it doesn’t exist already. This table has columns for id (auto-incrementing primary key), expression, and result.
  7. Inserting History:

    • insert_history(expression, result): Inserts a new record into the history table with the provided expression and result.
  8. Getting History:

    • get_history(): Retrieves the 10 most recent records from the history table.
  9. API Endpoints:

    • @app.route('/api/calculator/history', methods=['GET']): Defines an endpoint for getting calculator history.

      • It calls get_history() to retrieve data and returns it as JSON.
    • @app.route('/api/calculator/history', methods=["POST"]): Defines an endpoint for storing calculator results.

      • It extracts expression and result from the HTTP request and calls insert_history() to save the data.
  10. Main Execution:

    • if __name__ == '__main__':: Executes when the script is run directly (not imported as a module).
    • Calls create_table() to ensure the table exists.
    • Starts the Flask app with app.run().

Overall, this code sets up a Flask web application with routes to handle GET and POST requests for calculator history. It connects to a MySQL database to store and retrieve history records. The application also has CORS support enabled, allowing it to handle requests from different domains.

Links about front-end and back-end

This part will implement the input string and store the results in the back-end database. You can use the button to return to the previous calculation results, and view the history to read the last ten string formulas and corresponding calculation results, while linking the front and back ends.

<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        function store(expression, result) {
            console.log(expression, result)
            $.ajax({
                url: 'http://localhost:5000/api/calculator/history',
                type: 'post',
                data: {
                    expression: expression,
                    result: result
                }
            });
        }

        function getHistory() {
            $.ajax({
                url: 'http://localhost:5000/api/calculator/history',
                type: 'get',
                success: function (res) {
                    console.log(res);
                    // 创建表格
                    var table = $('<table>').addClass('history-table');

                    // 创建表头
                    var headerRow = $('<tr>');
                    headerRow.append($('<th>').text('ID'));
                    headerRow.append($('<th>').text('Formula'));
                    headerRow.append($('<th>').text('Result'));
                    table.append(headerRow);

                    // 填充数据
                    for (var i = 0; i < res.length; i++) {
                        var row = $('<tr>');
                        row.append($('<td>').text(res[i].id));
                        row.append($('<td>').text(res[i].formula));
                        row.append($('<td>').text(res[i].result));
                        table.append(row);
                    }

                    // 将表格添加到页面中
                    $('#history').html('');
                    $('#history').append(table);
                }
            });
        }

        function getAnswer() {
            $.ajax({
                url: 'http://localhost:5000/api/calculator/history',
                type: 'get',
                success: function (res) {
                    console.log(res["data"]["history"][0]["result"]);
                    var value = res["data"]["history"][0]["result"];
                    $('#text').val(value); // 将结果放到输入框中
                }
            });
        }

This JavaScript code is responsible for interacting with a web page that utilizes the Flask application you provided earlier. Here’s an explanation of the code:

  1. jQuery Library:

    • script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js": Includes the jQuery library. jQuery is a fast, small, and feature-rich JavaScript library that simplifies interactions with the DOM and handles AJAX requests.
  2. store function:

    • This function is responsible for sending a POST request to the server to store calculator results.
    • It takes two parameters: expression and result, which represent the mathematical expression and its computed result.
    • Uses $.ajax to make an asynchronous HTTP request to the specified URL (http://localhost:5000/api/calculator/history).
    • The request type is set to post, and the data being sent is an object containing expression and result.
    • This function is used for saving calculation history.
  3. getHistory function:

    • This function is triggered when a user requests to view the calculation history.
    • It sends a GET request to http://localhost:5000/api/calculator/history.
    • Upon success, it processes the response (res), which is expected to contain an array of history records.
    • It dynamically creates an HTML table to display the history and appends it to the element with the ID history.
  4. Creating the History Table:

    • The getHistory function dynamically creates an HTML table with headers (ID, Formula, Result) and fills it with data retrieved from the server.
  5. getAnswer function:

    • This function is used to retrieve the most recent calculation result from the server.
    • It sends a GET request to http://localhost:5000/api/calculator/history.
    • Upon success, it extracts the result from the response and updates an input field with the ID text to display this value.

Overall, this JavaScript code works in conjunction with the Flask application to handle user interactions on a web page. It uses AJAX to send requests to the server, receive responses, and update the page dynamically without requiring a full page refresh.

About the MySQL
在这里插入图片描述
在这里插入图片描述

Optimization of CSS

body {
    background:url(https://img1.baidu.com/it/u=1436390931,763795453&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=1082);
}

Product display:

video2

VII.Conclusion

This assignment is mainly to realize the separation of front-end and back-end, iteratively upgrade the basic calculator I made before, to achieve more expansion functions and to link and access the database. In this task, I learned the python flask framework and MySQL. The connection and application, and finally link the front and back ends to create a calculator with separate front and back ends.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值