Select Git revision
cron_fetch_networks.py
survey.py 3.00 KiB
import json
import logging
from pathlib import Path
from typing import Any, List, Optional
from flask import Blueprint, jsonify, request
from sqlalchemy import select
from compendium_v2.db import db
from compendium_v2.db.model import NREN
from compendium_v2.db.survey_model import Survey, SurveyResponse
from compendium_v2.routes import common
routes = Blueprint('survey', __name__)
logger = logging.getLogger(__name__)
# TODO (partial) schemas
@routes.route('/open', methods=['GET'])
@common.require_accepts_json
def open_survey() -> Any:
# just a hardcoded year and nren for development for now
nren = db.session.execute(select(NREN).order_by(NREN.id).limit(1)).scalar_one()
year = 1988
survey = db.session.scalar(select(Survey).where(Survey.year == year))
if survey is None or survey.survey == {}:
# TODO remove this at some point, its just convenient for now while we are changing the survey model a lot
p = Path(__file__).with_name('survey_model.json')
with p.open('r') as f:
survey = json.load(f)
# TODO add some magic strings in the json (like the year) and interpolate them here
data: Optional[dict] = None
page = 0
unvalidated: List[str] = [] # or should we keep track of what _was_ validated?
response = db.session.scalar(
select(SurveyResponse).where(SurveyResponse.survey_year == year).where(SurveyResponse.nren_id == nren.id)
)
previous_response = db.session.scalar(
select(SurveyResponse).where(SurveyResponse.survey_year == year - 1).where(SurveyResponse.nren_id == nren.id)
)
if response:
data = response.answers["data"]
page = response.answers["page"]
unvalidated = response.answers["unvalidated"]
elif previous_response:
data = previous_response.answers["data"]
unvalidated = ["TODO everything?"]
open_survey: dict = {
"model": survey,
"data": data,
"page": page,
"unvalidated": unvalidated
}
return jsonify(open_survey)
@routes.route('/save', methods=['POST'])
@common.require_accepts_json
def save_survey() -> Any:
# just a hardcoded year and nren for development for now
nren = db.session.execute(select(NREN).order_by(NREN.id).limit(1)).scalar_one()
year = 1988
survey = db.session.scalar(select(Survey).where(Survey.year == year))
if survey is None:
survey = Survey(year=year, survey={})
db.session.add(survey)
response = db.session.scalar(
select(SurveyResponse).where(SurveyResponse.survey_year == year).where(SurveyResponse.nren_id == nren.id)
)
if response is None:
response = SurveyResponse(survey_year=year, nren_id=nren.id)
db.session.add(response)
save_survey = request.json
if not save_survey:
raise Exception("Invalid format")
response.answers = {
"data": save_survey["data"],
"page": save_survey["page"],
"unvalidated": save_survey["unvalidated"]
}
db.session.commit()
return {'success': True}