Use WeChat mini program to separate front and back end calculator

832101202王志鹏
中国大学生计算机设计大赛二等奖获得者
2023-10-20 15:40:00
Course for This Assignmenthttps://bbs.csdn.net/forums/ssynkqtd-04?typeId=5171414
Assignment Requirementshttps://bbs.csdn.net/topics/617378696
Objectives of This AssignmentBack-end separation calculator programming
Other Referenceshttps://blog.csdn.net/Genio_Wang?type=bbs

Contents

  • 1. Interface Display
  • 2. Code Address
  • 3. PSP Form
  • 4. Design idea
  • 5. Front end
  • 6. Back-end
  • 7. Summary
  • Reference document

1. Interface Display

img


2. Code Address

Link1: Front end
Link2: Back end

3. PSP Form

Personal Software Process StagesEstimated Time minutesActual Time minutes
Planning2515
• Estimate2515
Development1130710
• Analysis6070
• Design Spec120150
• Design Review2010
• Coding Standard3010
• Design60100
• Coding600240
• Code Review60100
• Test18030
Reporting180120
• Test Repor12060
• Size Measurement2030
• Postmortem & Process Improvement Plan4030
Sum1335845

4. Design idea

This design implementation is an improvement on the basis of the first operation.

Front end part: Keep the existing calculator page, including HTML, CSS, and JavaScript code, and create a new page to display the history.
Back-end part: Writing the back end in Flask, after CORS is enabled, the front end will be able to communicate with the back end cross-domain, allowing the front end to get history from the back end. The back end provides two main Apis for adding computation records and getting computation records.
Database design: Create a MySQL database to store the user's computing history.

img

5. Front end

Page({
  data: {
    historyRecords: [] 
  },

  onLoad: function (options) {
    this.getHistoryFromServer();
  },

  getHistoryFromServer: function () {
    wx.request({
      url: 'http://127.0.0.1:5000',  
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        console.log('success', res.data.calculations);
        this.setData({ historyRecords: res.data.calculations });
      },
      fail: function (error) {
        console.error('fail', error);
      }
    });

  }
});

Page({ ... }): This is a core function in the applet framework that defines a page object that contains the page's data, lifecycle functions, and event handlers.

data: In this object, the data property defines the initial data of the page. In this example, data contains a property called historyRecords whose initial value is an empty array[]. This property will be used to store the history obtained from the server.

onLoad : onLoad is a lifecycle function that is automatically triggered when the page loads. Here, onLoad function calls the enclosing getHistoryFromServer () method, is used to get the history from the server.

getHistoryFromServer : This is a custom function for requesting history from the server. It uses the wx.request method of WeChat applet to initiate an HTTP GET request.

The main purpose of this code isto GET the history from the server through an HTTP GET request when the applet page loads, and then store the data in historyRecords.

6. Back-end

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

app = Flask(__name__)
CORS(app)  

app = Flask(__name__)

db = pymysql.connect(
   host='localhost',  
   user='root',       
   password='111111',   
   database='shujuku'    
)

@app.route('/addCalculation', methods=['POST'])
def add_calculation():
    try:
        data = request.get_json()
        content = data.get('content', '')
        result = data.get('result', '')

        cursor = db.cursor()
        sql = "INSERT INTO calculations (content, result) VALUES (%s, %s)"
        cursor.execute(sql, (content, result))
        db.commit()

        cursor.execute("SELECT LAST_INSERT_ID()")
        calculation_id = cursor.fetchone()[0]
        cursor.close()

        return jsonify({'success': True, 'id': calculation_id})
    except Exception as e:
        return jsonify({'success': False, 'message': 'fail', 'error': str(e)})

@app.route('/getCalculations', methods=['GET'])
def get_calculations():
    try:
        cursor = db.cursor()
        sql = "SELECT id, content, result FROM calculations"
        cursor.execute(sql)
        records = cursor.fetchall()
        calculations = [{'id': record[0], 'content': record[1], 'result': record[2]} for record in records]
        cursor.close()
        return jsonify({'success': True, 'calculations': calculations})
    except Exception as e:
        return jsonify({'success': False, 'message': 'fail', 'error': str(e)})


if __name__ == '__main__':
   app.run(host='0.0.0.0', port=5000, debug=True)

① Create a Flask application: Run app = Flask(__name__) to create a Flask application instance. CORS(app) means that CORS (cross-source Resource Sharing) support is enabled, allowing requests from different sources to access the backend.

② Database connection: Create a connection to the MySQL database through the pymysql module. Here, you specify the database host, username, password, and database name.

③ Processing functions: The back end defines two processing functions corresponding to the above two routes.

add_calculation() function: used to receive a POST request, get the data (calculated content and results) sent from the front-end applet, and then insert this data into the database. If the operation is successful, a success message in JSON format and the ID of the inserted record are returned.

get_calculations() function: used to receive GET requests, query all calculations from the database, and return these records to the front-end applet in JSON format.

7. Summary

This project needs to apply the relevant knowledge of the back-end database, which is also a part that I do not understand. The specific difficulty encountered in the actual operation is how to make the communication between the front and back end, which has troubled me for a long time, but I finally succeeded through searching materials and continuous practice.

Reference document

Link: WeChat open document

...全文
76 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

174

社区成员

发帖
与我相关
我的任务
社区描述
梅努斯软件工程
软件工程 高校 福建省·福州市
社区管理员
  • LinQF39
  • Jcandc
  • 助教-陈锦辉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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