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
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Unbound extensions shared across Flask application instances."""
import sqlite3
from flask import current_app, has_app_context
from flask_bootstrap import Bootstrap5
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_mail import Mail
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlalchemy.orm import DeclarativeBase
from .config import DEFAULT_SQLITE_PRAGMAS
from .tasks.extension import FlaskHuey
class Base(DeclarativeBase):
pass
csrf = CSRFProtect()
bootstrap = Bootstrap5()
db = SQLAlchemy(model_class=Base)
migrate = Migrate()
huey = FlaskHuey()
mail = Mail()
limiter = Limiter(key_func=get_remote_address)
@event.listens_for(Engine, "connect")
def set_sqlite_pragmas(connection: object, connection_record: object) -> None:
"""Apply the configured settings to each new SQLAlchemy SQLite connection.
App-managed connections use the current Flask app's validated settings.
Standalone SQLAlchemy connections use the documented defaults.
"""
if not isinstance(connection, sqlite3.Connection):
return
pragmas = (
current_app.config["SQLITE_PRAGMAS"]
if has_app_context() and "SQLITE_PRAGMAS" in current_app.config
else DEFAULT_SQLITE_PRAGMAS
)
# SQLite ignores foreign_keys inside a transaction. Python's sqlite3
# autocommit=False opens a transaction immediately, so temporarily enable
# autocommit while configuring the new DB-API connection.
previous_autocommit = connection.autocommit
connection.autocommit = True
try:
cursor = connection.cursor()
try:
cursor.execute("PRAGMA database_list")
file_backed = any(
name == "main" and bool(filename)
for _, name, filename in cursor.fetchall()
)
# Set lock waiting time before the WAL transition, which can lock.
if (timeout := pragmas["busy_timeout"]) is not None:
cursor.execute(f"PRAGMA busy_timeout = {timeout}")
for name in ("foreign_keys", "trusted_schema"):
if (enabled := pragmas[name]) is not None:
cursor.execute(f"PRAGMA {name} = {int(enabled)}")
# Journal modes apply to the database file, not in-memory SQLite.
if file_backed and (journal_mode := pragmas["journal_mode"]) is not None:
cursor.execute("PRAGMA journal_mode")
if cursor.fetchone()[0].upper() != journal_mode:
cursor.execute(f"PRAGMA journal_mode = {journal_mode}")
applied_mode = cursor.fetchone()[0].upper()
if applied_mode != journal_mode:
raise RuntimeError(
f"SQLite journal_mode {journal_mode} was not applied "
f"(using {applied_mode} instead)."
)
for name in ("synchronous", "cache_size"):
if (setting := pragmas[name]) is not None:
cursor.execute(f"PRAGMA {name} = {setting}")
if file_backed:
for name in ("wal_autocheckpoint", "journal_size_limit"):
if (setting := pragmas[name]) is not None:
cursor.execute(f"PRAGMA {name} = {setting}")
finally:
cursor.close()
finally:
connection.autocommit = previous_autocommit
|