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.
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.
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.
defsave_history(entry):withopen(history_file,'a')asfile:file.write(entry +'\n')defload_history():
history =[]withopen(history_file,'r')asfile:for line infile:
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('/')defindex():return render_template('index.html')@app.route('/calculate', methods=['POST'])defcalculate():
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'])defget_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"defsave_history(entry):withopen(history_file,'a')asfile:file.write(entry +'\n')defload_history():
history =[]withopen(history_file,'r')asfile:for line infile:
history.append(line.rstrip('\n'))return history
@app.route('/')defindex():return render_template('index.html')@app.route('/calculate', methods=['POST'])defcalculate():
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'])defget_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.