-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
156 lines (128 loc) · 4.52 KB
/
app.py
File metadata and controls
156 lines (128 loc) · 4.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import json
import os
from flask import Flask, render_template, request, flash, redirect, url_for
from flask_mail import Mail, Message as MailMessage
import mysql.connector
from config import Config
app = Flask(__name__)
app.config.from_object(Config)
mail = Mail(app)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECTS_PATH = os.path.join(BASE_DIR, "data", "projects.json")
def get_db():
"""Return a MySQL connection."""
return mysql.connector.connect(
host=app.config["DB_HOST"],
port=app.config["DB_PORT"],
user=app.config["DB_USER"],
password=app.config["DB_PASSWORD"],
database=app.config["DB_NAME"],
ssl_disabled=app.config.get("DB_SSL_DISABLED", True),
)
def init_db():
"""Create the contact_messages table if it doesn't exist."""
try:
conn = get_db()
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS contact_messages (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(120) NOT NULL,
subject VARCHAR(200) NOT NULL,
message TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
)
conn.commit()
cursor.close()
conn.close()
except mysql.connector.Error as err:
print(f"[DB INIT WARNING] Could not initialize database: {err}")
def load_projects():
"""Load projects from the JSON file."""
try:
with open(PROJECTS_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return []
@app.route("/")
def index():
projects = load_projects()
featured = [p for p in projects if p.get("featured")]
regular = [p for p in projects if not p.get("featured")]
return render_template(
"index.html",
projects=projects,
featured_project=featured[0] if featured else None,
regular_projects=regular,
)
@app.route("/contact", methods=["POST"])
def contact():
name = request.form.get("name", "").strip()
email = request.form.get("email", "").strip()
subject = request.form.get("subject", "").strip()
message = request.form.get("message", "").strip()
if not all([name, email, subject, message]):
flash("All fields are required.", "error")
return redirect(url_for("index") + "#contact")
if "@" not in email or "." not in email:
flash("Please enter a valid email address.", "error")
return redirect(url_for("index") + "#contact")
# Try saving to database (non-blocking)
db_saved = False
try:
conn = get_db()
cursor = conn.cursor()
cursor.execute(
"INSERT INTO contact_messages (name, email, subject, message) VALUES (%s, %s, %s, %s)",
(name, email, subject, message),
)
conn.commit()
cursor.close()
conn.close()
db_saved = True
except mysql.connector.Error as err:
print(f"[DB ERROR] {err}")
# Send email notification (always attempted)
email_sent = False
try:
if app.config["MAIL_USERNAME"]:
body = f"Name: {name}\nEmail: {email}\nSubject: {subject}\n\nMessage:\n{message}"
if not db_saved:
body += "\n\n[NOTE] Database was unavailable - this message was NOT saved to DB."
msg = MailMessage(
subject=f"Portfolio Contact: {subject}",
recipients=[app.config["ADMIN_EMAIL"]],
body=body,
)
mail.send(msg)
email_sent = True
except Exception as err:
print(f"[MAIL ERROR] {err}")
if email_sent or db_saved:
flash("Thank you! Your message has been sent successfully.", "success")
else:
flash("Could not send your message. Please try again later.", "error")
return redirect(url_for("index") + "#contact")
@app.route("/healthz")
def health_check():
status = {"app": "ok"}
try:
conn = get_db()
conn.close()
status["db"] = "ok"
except Exception:
status["db"] = "unavailable"
return status, 200
@app.errorhandler(404)
def not_found(e):
return render_template("index.html", projects=load_projects()), 404
@app.errorhandler(500)
def server_error(e):
return render_template("index.html", projects=load_projects()), 500
if __name__ == "__main__":
init_db()
app.run(host="0.0.0.0", debug=app.config["DEBUG"], port=5000)