def _jsonify(connection: Connection, answer: object, question_id: str) -> object: """ This function returns a "nice" representation of an answer which can be serialized as JSON. :param connection: a SQLAlchemy Connection :param answer: a submitted value :param type_constraint_name: the UUID of the question :return: the nice representation """ type_constraint_name = question_select(connection, question_id).type_constraint_name if type_constraint_name in {'location', 'facility'}: geo_json = connection.execute(func.ST_AsGeoJSON(answer)).scalar() return json_decode(geo_json)['coordinates'] elif type_constraint_name in {'date', 'time'}: return maybe_isoformat(answer) elif type_constraint_name == 'decimal': return float(answer) elif type_constraint_name == 'multiple_choice': question_choice = question_choice_select(connection, answer) return question_choice.choice else: return answer
def testQuestionChoiceSelect(self): q_where = question_table.select().where( question_table.c.type_constraint_name == 'multiple_choice') question_id = connection.execute(q_where).first().question_id choice_id = get_choices(connection, question_id).first().question_choice_id choice = question_choice_select(connection, choice_id) self.assertIsNotNone(choice) self.assertRaises(QuestionChoiceDoesNotExistError, question_choice_select, connection, str(uuid.uuid4()))
def _get_fields(connection: Connection, answer: RowProxy) -> dict: """ Extract the relevant fields for an answer (from the answer or answer_choice table). :param connection: a SQLAlchemy connection :param answer: A record in the answer or answer_choice table :return: A dictionary of the fields. """ tcn = answer.type_constraint_name question_id = answer.question_id question = question_select(connection, question_id) result_dict = {'question_id': question_id, 'question_title': question.question_title, 'sequence_number': question.sequence_number, 'type_constraint_name': tcn, 'is_type_exception': _get_is_type_exception(answer)} try: # Get the choice for a multiple choice question choice_id = answer.question_choice_id result_dict['answer'] = choice_id result_dict['answer_choice_metadata'] = answer.answer_choice_metadata result_dict['answer_id'] = answer.answer_choice_id choice = question_choice_select(connection, choice_id) result_dict['choice'] = choice.choice result_dict['choice_number'] = choice.choice_number except AttributeError: # The answer is not a choice question = question_select(connection, answer.question_id) if answer.is_type_exception: tcn = 'text' result_dict['answer'] = _jsonify(connection, answer, tcn) result_dict['answer_metadata'] = answer.answer_metadata result_dict['answer_id'] = answer.answer_id result_dict['choice'] = None result_dict['choice_number'] = None return result_dict