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/
│── [Link] # Main Flask app
│── templates/
│ ├── [Link] # Frontend UI
│── static/
│ ├── [Link] # CSS for styling
│── [Link] # SQLite database (auto-created)
3️⃣ Python Code ([Link])
Create [Link] inside your project folder:
python
CopyEdit
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
import math
app = Flask(__name__)
[Link]['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///[Link]'
[Link]['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Database Model
class History([Link]):
id = [Link]([Link], primary_key=True)
num1 = [Link]([Link], nullable=True)
num2 = [Link]([Link], nullable=True)
operator = [Link]([Link](5), nullable=False)
result = [Link]([Link](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 [Link](num1, num2)
elif operator == 'sqrt': return [Link](num1)
elif operator == 'log': return [Link](num1) if num1 > 0 else 'Error'
elif operator == 'sin': return [Link]([Link](num1))
elif operator == 'cos': return [Link]([Link](num1))
elif operator == 'tan': return [Link]([Link](num1))
else: return 'Invalid Operation'
except Exception as e:
return f"Error: {str(e)}"
# Home Route
@[Link]("/", methods=["GET", "POST"])
def index():
result = None
if [Link] == "POST":
num1 = float([Link]("num1", 0))
num2 = float([Link]("num2", 0))
operator = [Link]("operator", "")
result = calculate(num1, num2, operator)
# Save to database
history_entry = History(num1=num1, num2=num2, operator=operator,
result=str(result))
[Link](history_entry)
[Link]()
history = [Link].order_by([Link]()).limit(10).all()
return render_template("[Link]", result=result, history=history)
# Clear History
@[Link]("/clear", methods=["POST"])
def clear_history():
[Link](History).delete()
[Link]()
return redirect("/")
# Initialize Database
with app.app_context():
db.create_all()
if __name__ == "__main__":
[Link](debug=True)
4️⃣ HTML Code (templates/[Link])
Create a templates folder and inside it, add [Link]:
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='[Link]') }}">
</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 }} {{ [Link] }} {{ entry.num2 }} = {{ [Link] }}</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() {
[Link]('dark-mode');
[Link]('darkMode', [Link]('dark-mode')
? 'enabled' : 'disabled');
[Link] = function () {
if ([Link]('darkMode') === 'enabled') {
[Link]('dark-mode');
};
</script>
</body>
</html>
5️⃣ CSS Styling (static/[Link])
Create a static folder and inside it, add [Link]:
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 [Link]
3⃣ Open your browser and go to:
cpp
CopyEdit
[Link]
Done! Your Flask calculator is now fully functional with dark mode, history, and
database support!