Pythoncode with steps
Pythoncode with steps
sh
CopyEdit
csharp
CopyEdit
calculator_project/
│── templates/
│── static/
CopyEdit
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)
try:
elif operator == '/': return num1 / num2 if num2 != 0 else 'Error: Division by zero'
except Exception as e:
# Home Route
def index():
result = None
if request.method == "POST":
# Save to database
db.session.add(history_entry)
db.session.commit()
history = History.query.order_by(History.id.desc()).limit(10).all()
@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)
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<form method="POST">
<select name="operator">
</select>
</form>
{% endif %}
<h3>Calculation History</h3>
<div class="history-container">
<ul>
{% for entry in history %}
{% endfor %}
</ul>
</div>
</form>
</div>
<script>
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
localStorage.setItem('darkMode', document.body.classList.contains('dark-mode')
? 'enabled' : 'disabled');
window.onload = function () {
document.body.classList.add('dark-mode');
};
</script>
</body>
</html>
5️⃣ CSS Styling (static/styles.css)
css
CopyEdit
body {
text-align: center;
background-color: #f4f4f4;
color: black;
.dark-mode {
background-color: #222;
color: white;
.container {
width: 450px;
margin: auto;
padding: 20px;
background: white;
border-radius: 10px;
.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;
sh
CopyEdit
cd calculator_project
sh
CopyEdit
python app.py
cpp
CopyEdit
http://127.0.0.1:5000/
Done! Your Flask calculator is now fully functional with dark mode, history, and
database support!