01. Apache and Flask: different jobs
Apache is an HTTP server, commonly used for static assets, TLS certificates and reverse proxying. Flask is a Python web framework: it defines routes, renders templates, handles forms, enforces application rules and exposes APIs. Flask is not a direct drop-in replacement for everything Apache does.
Recommended for an existing Apache site: keep Apache as the public entry point and reverse-proxy an application path such as /todo/ to a local Flask process. Static pages can continue to be served by Apache. Alternatively, a dedicated reverse proxy such as Nginx or Caddy can front Flask.
| Concern | Static Apache site | Flask application |
|---|---|---|
| Pages | Files served as-is | Routes can generate dynamic responses |
| Forms & logins | Usually need additional application logic | Handled in Python routes and extensions |
| HTTPS & public connections | Apache handles directly | Usually delegated to a reverse proxy |
| Data | Files, or external services | JSON, SQLite, PostgreSQL and more |
02. Create a minimal Flask application
Use a virtual environment so application dependencies do not conflict with Arch Linux's system Python. This is a standalone demonstration; do not overwrite your existing FixUpFairies application.
sudo pacman -Syu --needed python python-pip
mkdir -p ~/flask-json-demo && cd ~/flask-json-demo
python -m venv .venv
.venv/bin/python -m pip install Flask gunicornCreate app.py:
from flask import Flask, jsonify, render_template_string
app = Flask(__name__)
@app.get("/")
def home():
return render_template_string("<h1>Hello from Flask!</h1>")
@app.get("/api/health")
def health():
return jsonify(status="ok")Test locally, then stop the development server with Ctrl+C:
.venv/bin/flask --app app run --host 127.0.0.1 --port 8000
# In another terminal:
curl http://127.0.0.1:8000/api/health03. Production: Gunicorn, systemd and Apache
Gunicorn runs Flask as a production WSGI application. The example below uses a single worker to keep a small JSON-backed application simple; proper file locking is still necessary if other processes write to the same files.
Create a systemd service, adjusting paths and account names for your installation:
# /etc/systemd/system/flask-json-demo.service
[Unit]
Description=Flask JSON demo
After=network.target
[Service]
Type=simple
User=tc001
Group=tc001
WorkingDirectory=/home/tc001/flask-json-demo
ExecStart=/home/tc001/flask-json-demo/.venv/bin/gunicorn --workers 1 --bind 127.0.0.1:8000 app:app
Restart=on-failure
RestartSec=5
NoNewPrivileges=true
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable --now flask-json-demo.service
sudo systemctl status flask-json-demo.service --no-pager
curl http://127.0.0.1:8000/api/healthFor an existing Apache HTTPS virtual host, add a dedicated reverse-proxy mapping. Ensure mod_proxy, mod_proxy_http and any required SSL modules are enabled, and avoid conflicting path rules:
# Inside the appropriate existing Apache VirtualHost
ProxyPreserveHost On
ProxyPass /demo/ http://127.0.0.1:8000/
ProxyPassReverse /demo/ http://127.0.0.1:8000/sudo httpd -t
sudo systemctl reload httpd.service/demo/ prefix is illustrative. Applications that generate URLs, redirects, cookies or static-file links must be configured for their external mount prefix (for example using ProxyFix only with trusted proxy settings and an appropriate SCRIPT_NAME/prefix strategy). Test authentication and links before production use. Never blindly paste this into the live /todo/ configuration.04. JSON instead of a traditional SQL database
JSON is a human-readable data format, not a database engine. For a small application it can be practical to store settings, modest task lists or project metadata as files. Python's json module reads and writes the format without a separate database server.
{
"projects": [
{"id": "p-001", "name": "Website refresh", "done": false},
{"id": "p-002", "name": "Traffic dashboard", "done": true}
]
}| Consideration | JSON files | SQLite / SQL |
|---|---|---|
| Setup | Very simple; no DB service | SQLite also needs no separate server |
| Queries | Load and filter in Python | Indexes and SQL queries |
| Concurrent writes | Application must coordinate | Transactions handled by DB engine |
| Relationships | Maintained manually | Constraints and joins available |
| Best fit | Small, low-write datasets and config | Growing or frequently updated application data |
Rule of thumb: JSON works well when the entire file is small and updates are infrequent. When many users write simultaneously, the dataset grows, or you need reliable transactions across multiple records, use SQLite or a database server.
05. What goes wrong with naive JSON writes?
Suppose two Flask workers read the same file, each adds a task, and both write it back. The second write can silently erase the first. This is a lost update. A process crash while writing directly to the target file can also leave truncated or invalid JSON.
Avoid these anti-patterns:
# Unsafe if multiple requests/processes can update the file:
data = json.loads(path.read_text())
data["counter"] += 1
path.write_text(json.dumps(data))Two separate protections are needed: an interprocess lock around the entire read–modify–write transaction, and an atomic replacement so readers never see a partially written destination file.
06. Safe JSON storage with a persistent lock file
On a single Arch Linux host, the standard-library fcntl.flock provides advisory locks between cooperating processes. Use a separate, persistent .lock file; do not lock the JSON data file and then replace that same file, because replacement changes its inode. All code paths that write the data must use the same lock.
Create json_store.py alongside your Flask app:
import json
import os
import tempfile
from contextlib import contextmanager
from pathlib import Path
import fcntl
DATA = Path("/home/tc001/flask-json-demo/data/tasks.json")
LOCK = DATA.with_name(DATA.name + ".lock")
@contextmanager
def exclusive_lock():
DATA.parent.mkdir(parents=True, exist_ok=True)
# Keep this lock file: do not unlink it after each operation.
with LOCK.open("a+b") as lock_file:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
def read_unlocked():
try:
with DATA.open("r", encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
return {"tasks": []} # Only missing files use a default.
def atomic_write(data):
# Called only while holding exclusive_lock().
fd, temp_name = tempfile.mkstemp(
prefix=".tasks-", suffix=".tmp", dir=DATA.parent
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
f.write("\n")
f.flush()
os.fsync(f.fileno())
os.replace(temp_name, DATA) # Same filesystem.
# Flush the directory entry for stronger crash durability on Linux.
dir_fd = os.open(DATA.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(dir_fd)
finally:
os.close(dir_fd)
finally:
if os.path.exists(temp_name):
os.unlink(temp_name)
def add_task(title):
with exclusive_lock():
data = read_unlocked()
data["tasks"].append({"title": title, "done": False})
atomic_write(data)
return len(data["tasks"])
def list_tasks():
with exclusive_lock():
return read_unlocked()["tasks"]os.replace() atomically switches the destination to a complete JSON document. Readers using the same lock also receive a consistent snapshot.The code deliberately does not treat malformed JSON as an empty database. If a file is corrupt, fail visibly, preserve evidence and restore from a backup rather than overwriting it.
Use it from Flask
from flask import request, jsonify
from json_store import add_task, list_tasks
@app.get("/api/tasks")
def tasks():
return jsonify(list_tasks())
@app.post("/api/tasks")
def create_task():
payload = request.get_json(silent=True) or {}
title = payload.get("title")
if not isinstance(title, str) or not title.strip():
return jsonify(error="A non-empty title is required"), 400
count = add_task(title.strip()[:200])
return jsonify(count=count), 20107. Prevent locking problems and lost updates
Locks are useful, but poor lock design can cause contention or deadlocks. These practices keep JSON applications reliable:
- Lock the whole transaction: acquire the lock before reading, then modify and atomically replace before releasing it.
- Keep critical sections short: do not make network calls, send emails or wait for user input while holding the lock.
- Use one consistent lock path: every Flask worker, CLI script, timer and maintenance task must cooperate on the same lock file.
- Never delete a lock file during normal operation: deleting and recreating it can let processes lock different inodes.
- Choose lock ordering: if you must lock multiple files, always acquire locks in the same deterministic order; better yet, avoid cross-file transactions with JSON.
- Handle failures: return a clear error if disk space, permissions or JSON decoding fail. Do not silently reset the dataset.
- Limit write frequency: debounce frequent changes or queue writes where appropriate, but remember that queues need their own reliability design.
- Monitor duration: track slow operations and consider a bounded non-blocking retry strategy if waiting for a lock becomes a problem.
Optional: fail quickly rather than wait indefinitely
The earlier example uses blocking LOCK_EX. For a service where prompt errors are preferable, use LOCK_EX | LOCK_NB and catch BlockingIOError to return an HTTP 503 or retry with a bounded backoff. Avoid tight infinite retry loops.
try:
fcntl.flock(lock_file.fileno(),
fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
# Busy: retry briefly or return a controlled error.
raise RuntimeError("JSON store is busy")Scope: flock is suitable for cooperating processes on one Linux host and local filesystem. Do not assume identical semantics on NFS, cloud-synced folders, multiple servers or containers with independent filesystems. A Python threading.Lock alone does not coordinate separate Gunicorn worker processes.
08. When to switch to SQLite or PostgreSQL
JSON is not inherently more robust than SQL. SQLite is included with Python, stores data in one file and provides transactions, indexes, constraints and built-in concurrency controls. For many small Flask applications, it is the best next step when JSON updates become complex.
import sqlite3
with sqlite3.connect("tasks.sqlite3", timeout=10) as db:
db.execute("""CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0
)""")
db.execute("INSERT INTO tasks(title) VALUES (?)", ("Check backups",))Consider SQLite when users frequently edit tasks or projects, data must be queried or filtered, or several related records must change together. Consider PostgreSQL for heavier multi-user workloads, multiple application hosts or operational requirements that justify a database server.
09. Security, backups and operations
- Keep data private: store JSON outside
/srv/httpand Flask's publicstatic/directory. - Use least privilege: run Gunicorn as a dedicated unprivileged service user; restrict directory and file permissions.
- Validate inputs: reject unexpected JSON structures and oversized requests; enforce authorization on every write route.
- Protect sessions: configure a strong Flask secret key, secure cookies, HTTPS and CSRF protection for browser forms.
- Back up consistently: acquire the same lock when taking a JSON snapshot, or otherwise coordinate writes; test restores.
- Monitor errors: review
journalctl -u flask-json-demo.service, application exceptions and disk-space alerts. - Keep versions current: update Flask, Gunicorn, Python and Arch packages in a controlled manner.
- Plan growth: document when you will migrate from JSON to SQLite or PostgreSQL.
Quick production checks
sudo systemctl status flask-json-demo.service --no-pager
sudo journalctl -u flask-json-demo.service -n 50 --no-pager
sudo httpd -t
curl -i http://127.0.0.1:8000/api/health
ls -ld /home/tc001/flask-json-demo/data10. Deployment checklist
Tick each item as you verify it. This checklist is not stored on the server.
0 of 9 complete
11. Further reading
- Flask — Deploying to Production
- Flask — Tell Flask it is Behind a Proxy
- Gunicorn — Deploying Gunicorn
- Python — json module
- Python — fcntl module
- Python — os.replace
- SQLite — Appropriate Uses
- Apache — mod_proxy
Review upstream documentation and test changes in staging before modifying production services.