This commit is contained in:
m
2026-03-17 09:16:51 +01:00
parent f7feb18de3
commit cd0c11dec3

93
flask_logic/logic.py Normal file
View File

@@ -0,0 +1,93 @@
import os
import csv
COMMENT_FILE = os.path.join(os.path.dirname(__file__), '../content/comments.csv')
MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024 # 5MB example
import datetime
def save_comment(post_id, author, content):
"""Handles the validation and saving of comments to the private CSV."""
# 1. Validation logic moved here
if not content or len(content) > 1000:
return False
author = (author or "Anonymous").strip()[:50]
content = content.strip()
# 2. Path & Size Checks
file_exists = os.path.isfile(COMMENT_FILE)
if file_exists and os.path.getsize(COMMENT_FILE) > MAX_FILE_SIZE_BYTES:
return False # Or raise a specific error
# 3. Write to CSV
with open(COMMENT_FILE, 'a', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=['post_id', 'author', 'content', 'date'])
if not file_exists:
writer.writeheader()
writer.writerow({
'post_id': post_id,
'author': author,
'content': content,
'date': datetime.datetime.now().strftime("%B %d, %Y at %I:%M %p")
})
return True
def load_snippet(filename):
"""Helper to read HTML snippets from the data folder."""
base_path = os.path.join(os.path.dirname(__file__), 'data')
file_path = os.path.join(base_path, filename)
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()
return ""
def get_enriched_post(post_id, BLOG_POSTS):
post = next((p for p in BLOG_POSTS if p.get('id') == post_id), None)
if not post:
return None
# Mapping config: keeps logic.py tiny
configs = {
10: {
"template": "components/timeline.html",
"timeline_file": "post_10_timeline.html"
},
8: {
"template": "components/christmas_post.html",
"timeline": None
},
}
if post_id in configs:
conf = configs[post_id]
post_template = conf.get("template")
if post_template:
post["template"] = post_template
# Only load the file if a filename is provided
t_file = conf.get("timeline_file")
if t_file:
post["timeline"] = load_snippet(t_file)
return post
def get_comments_for_post(post_id):
comments = []
if not os.path.exists(COMMENT_FILE):
return comments
if os.path.getsize(COMMENT_FILE) > MAX_FILE_SIZE_BYTES:
return ["Comment section full."] # Handle error in app.py
with open(COMMENT_FILE, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
if row['post_id'] == str(post_id):
comments.append(row)
return comments