174
社区成员
![](https://csdnimg.cn/release/cmsfe/public/img/topic.427195d5.png)
![](https://csdnimg.cn/release/cmsfe/public/img/me.40a70ab0.png)
![](https://csdnimg.cn/release/cmsfe/public/img/task.87b52881.png)
![](https://csdnimg.cn/release/cmsfe/public/img/share-circle.3e0b7822.png)
Course for This Assignment | https://bbs.csdn.net/forums/ssynkqtd-04?typeId=5171414 |
---|---|
Assignment Requirements | https://bbs.csdn.net/topics/617378696 |
Objectives of This Assignment | Back-end separation calculator programming |
Other References | https://blog.csdn.net/Genio_Wang?type=bbs |
Link1: Front end
Link2: Back end
Personal Software Process Stages | Estimated Time minutes | Actual Time minutes |
---|---|---|
Planning | 25 | 15 |
• Estimate | 25 | 15 |
Development | 1130 | 710 |
• Analysis | 60 | 70 |
• Design Spec | 120 | 150 |
• Design Review | 20 | 10 |
• Coding Standard | 30 | 10 |
• Design | 60 | 100 |
• Coding | 600 | 240 |
• Code Review | 60 | 100 |
• Test | 180 | 30 |
Reporting | 180 | 120 |
• Test Repor | 120 | 60 |
• Size Measurement | 20 | 30 |
• Postmortem & Process Improvement Plan | 40 | 30 |
Sum | 1335 | 845 |
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.
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
.
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.
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.
Link: WeChat open document