Files
WebApi/examples/serve_cama_cohort.py
T
2026-11-13 17:54:56 -06:00

52 lines
1.5 KiB
Python

"""Run the cohort endpoints locally against an explicitly supplied synthetic SQLite file."""
import os
from pathlib import Path
import sqlite3
from urllib.parse import quote
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
if os.name == 'nt':
import sys
import types
fcntl = types.ModuleType('fcntl')
fcntl.LOCK_EX, fcntl.LOCK_UN = 2, 8
def unavailable(*args):
raise RuntimeError('File locking is unavailable in this local Windows example')
fcntl.flock = unavailable
sys.modules['fcntl'] = fcntl
path = Path(os.environ['CAMA_SYNTHETIC_SQLITE']).resolve(strict=True)
if not path.is_file():
raise ValueError('The synthetic SQLite database must already exist')
# The cohort reader can only open the named file in read-only mode.
uri = 'file:' + quote(path.as_posix(), safe='/:') + '?mode=ro'
engine = create_engine('sqlite://', creator=lambda: sqlite3.connect(uri, uri=True))
# The other application blueprints must not inherit a live database URL.
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'):
os.environ[domain + '_DATABASE_URL'] = 'sqlite:///:memory:'
from webapi import create_app
from webapi.cama_cohort import CamaCohort
app = create_app()
def read(cutoff):
with Session(engine) as session:
return CamaCohort(session).rows(cutoff)
app.config['CAMA_COHORT_READER'] = read
if __name__ == '__main__':
app.run(host='127.0.0.1', port=int(os.environ.get('CAMA_COHORT_PORT', '5059')), debug=False)