Select Git revision
      
  dump_survey_model.py
              Bjarke Madsen authored 
   dump_survey_model.py  1.74 KiB 
"""
dump survey model
=========================
This module dumps a survey model to file to check into git,
so that changes can be tracked.
The dumped survey model should afterwards be committed back
to the database with a migration script.
See b3e1c5149181_insert_survey_model_2022.py for such a script.
Create a revision with `flask db revision` and then just copy paste the new model and year.
If the --year option is not supplied, the newest survey will be dumped.
"""
import logging
import click
import json
import os
from sqlalchemy import select
import compendium_v2
from compendium_v2.environment import setup_logging
from compendium_v2.db import db
from compendium_v2.config import load
from compendium_v2.db.survey_model import Survey
setup_logging()
logger = logging.getLogger('dump_survey_model')
def _write_survey_model(survey, filename):
    with open(filename, "w") as out:
        json.dump(survey.survey, out, indent=1)
    print(f"Dumped survey model to {filename}")
def _cli(app, year):
    query = select(Survey).where(Survey.year == year) if year else select(Survey).order_by(Survey.year.desc()).limit(1)
    with app.app_context():
        survey = db.session.scalar(query)
        if not survey:
            raise Exception('Survey not found')
        filename = "survey_model_" + str(survey.year) + ".json"
        dump_file = os.path.join(os.path.dirname(__file__), 'surveymodels', filename)
        _write_survey_model(survey, dump_file)
@click.command()
@click.option('--config', type=click.STRING, default='config.json')
@click.option('--year', type=click.INT)
def cli(config, year):
    app_config = load(open(config, 'r'))
    app = compendium_v2._create_app_with_db(app_config)
    _cli(app, year)
if __name__ == "__main__":
    cli()