Converting PHP to Python (Flask)
• We will use Flask for the web framework.
• SQLite as the database instead of MySQL (for simplicity).
• The project will include:
o A calculator with multiple operations.
o A dark mode toggle using JavaScript.
o A history log stored in the database.
1️⃣ Install Required Packages
Before running the project, install Flask and SQLite support:
sh
CopyEdit
pip install flask flask_sqlalchemy
2️⃣ Project Structure
csharp
CopyEdit
calculator_project/
│── app.py # Main Flask app
│── templates/
│ ├── index.html # Frontend UI
│── static/
│ ├── styles.css # CSS for styling
│── database.db # SQLite database (auto-created)
3️⃣ Python Code (app.py)
Create app.py inside your project folder:
python
CopyEdit
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
import math
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Database Model
class History(db.Model):
id = db.Column(db.Integer, primary_key=True)
num1 = db.Column(db.Float, nullable=True)
num2 = db.Column(db.Float, nullable=True)
operator = db.Column(db.String(5), nullable=False)
result = db.Column(db.String(50), nullable=False)
# Function to perform calculations
def calculate(num1, num2, operator):
try:
if operator == '+': return num1 + num2
elif operator == '-': return num1 - num2
elif operator == '*': return num1 * num2
elif operator == '/': return num1 / num2 if num2 != 0 else 'Error: Division by zero'
elif operator == '%': return num1 % num2 if num2 != 0 else 'Error'
elif operator == '^': return math.pow(num1, num2)
elif operator == 'sqrt': return math.sqrt(num1)
elif operator == 'log': return math.log(num1) if num1 > 0 else 'Error'
elif operator == 'sin': return math.sin(math.radians(num1))
elif operator == 'cos': return math.cos(math.radians(num1))
elif operator == 'tan': return math.tan(math.radians(num1))
else: return 'Invalid Operation'
except Exception as e:
return f"Error: {str(e)}"
# Home Route
@app.route("/", methods=["GET", "POST"])
def index():
result = None
if request.method == "POST":
num1 = float(request.form.get("num1", 0))
num2 = float(request.form.get("num2", 0))
operator = request.form.get("operator", "")
result = calculate(num1, num2, operator)
# Save to database
history_entry = History(num1=num1, num2=num2, operator=operator,
result=str(result))
db.session.add(history_entry)
db.session.commit()
history = History.query.order_by(History.id.desc()).limit(10).all()
return render_template("index.html", result=result, history=history)
# Clear History
@app.route("/clear", methods=["POST"])
def clear_history():
db.session.query(History).delete()
db.session.commit()
return redirect("/")
# Initialize Database
with app.app_context():
db.create_all()
if __name__ == "__main__":
app.run(debug=True)
4️⃣ HTML Code (templates/index.html)
Create a templates folder and inside it, add index.html:
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SmartCalc - Flask Calculator</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<div class="container">
<h2>SmartCalc - Flask Calculator</h2>
<form method="POST">
<input type="number" name="num1" placeholder="Enter first number" required>
<input type="number" name="num2" placeholder="Enter second number">
<select name="operator">
<option value="+">Addition (+)</option>
<option value="-">Subtraction (-)</option>
<option value="*">Multiplication (*)</option>
<option value="/">Division (/)</option>
<option value="%">Modulus (%)</option>
<option value="^">Exponentiation (^)</option>
<option value="sqrt">Square Root (√)</option>
<option value="log">Logarithm (log)</option>
<option value="sin">Sine (sin)</option>
<option value="cos">Cosine (cos)</option>
<option value="tan">Tangent (tan)</option>
</select>
<button type="submit" class="btn">Calculate</button>
</form>
{% if result is not none %}
<h3>Result: {{ result }}</h3>
{% endif %}
<h3>Calculation History</h3>
<div class="history-container">
<ul>
{% for entry in history %}
<li>{{ entry.num1 }} {{ entry.operator }} {{ entry.num2 }} = {{ entry.result }}</li>
{% endfor %}
</ul>
</div>
<form method="POST" action="/clear">
<button type="submit" class="btn clear-btn">Clear History</button>
</form>
<button onclick="toggleDarkMode()" class="btn toggle-btn">Toggle Dark
Mode</button>
</div>
<script>
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
localStorage.setItem('darkMode', document.body.classList.contains('dark-mode')
? 'enabled' : 'disabled');
window.onload = function () {
if (localStorage.getItem('darkMode') === 'enabled') {
document.body.classList.add('dark-mode');
};
</script>
</body>
</html>
5️⃣ CSS Styling (static/styles.css)
Create a static folder and inside it, add styles.css:
css
CopyEdit
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f4f4f4;
color: black;
transition: background 0.3s, color 0.3s;
.dark-mode {
background-color: #222;
color: white;
.container {
width: 450px;
margin: auto;
padding: 20px;
background: white;
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
.dark-mode .container {
background: #333;
color: white;
.history-container {
max-height: 150px;
overflow-y: auto;
background: #f9f9f9;
padding: 10px;
border-radius: 5px;
.dark-mode .history-container {
background: #444;
6️⃣ Running the Project
1⃣ Navigate to your project folder:
sh
CopyEdit
cd calculator_project
2⃣ Run the Flask app:
sh
CopyEdit
python app.py
3⃣ Open your browser and go to:
cpp
CopyEdit
http://127.0.0.1:5000/
Done! Your Flask calculator is now fully functional with dark mode, history, and
database support!