コード例 #1
0
ファイル: first_time.py プロジェクト: wovari/scoremodel
def add_lang():
    languages = app.config['LANGUAGES']
    lang_api = LangApi()
    if len(languages) == 0:
        languages.append('en')
    for lang in languages:
        try:
            lang_api.by_lang(lang)
        except DatabaseItemDoesNotExist:
            lang_api.create({'lang': lang})
コード例 #2
0
class ReportApi(GenericApi):
    simple_params = ['title', 'lang_id']
    complex_params = []
    possible_params = ['title', 'lang_id']
    required_params = ['title', 'lang_id']

    def __init__(self, report_id=None, autocommit=True):
        self.report_id = report_id
        self.lang_api = LangApi()
        self.autocommit = autocommit

    def create(self, input_data):
        """
        Create a new report. See QuestionApi.create()
        :param input_data:
        :param autocommit:
        :return:
        """
        cleaned_data = self.parse_input_data(input_data)
        if self.db_exists(cleaned_data['title']):
            raise DatabaseItemAlreadyExists(_e['item_exists'].format(
                Report, cleaned_data['title']))
        return self.db_create(cleaned_data)

    def read(self, report_id):
        """
        Get a report by its id. See QuestionApi.read()
        :param report_id:
        :return:
        """
        existing_report = Report.query.filter(Report.id == report_id).first()
        if existing_report is None:
            raise DatabaseItemDoesNotExist(_e['item_not_exists'].format(
                Report, report_id))
        return existing_report

    def update(self, report_id, input_data):
        """
        Update an existing report. See QuestionApi.update()
        :param report_id:
        :param input_data:
        :param autocommit:
        :return:
        """
        cleaned_data = self.parse_input_data(input_data)
        existing_report = self.read(report_id)
        return self.db_update(existing_report, cleaned_data)

    def delete(self, report_id, autocommit=None):
        """
        Delete an existing report. See QuestionApi.delete()
        :param report_id:
        :param autocommit:
        :return:
        """
        existing_report = self.read(report_id)
        db.session.delete(existing_report)
        self.store(autocommit)
        return True

    def list(self):
        """
        List all reports
        :return:
        """
        existing_reports = Report.query.all()
        return existing_reports

    def by_lang(self, lang):
        """
        List all reports in a given language
        :return:
        """
        existing_lang = self.lang_api.by_lang(lang)
        existing_reports = Report.query.filter(
            Report.lang_id == existing_lang.id).all()
        return existing_reports

    def parse_input_data(self, input_data):
        """
        Clean the input data dict: remove all non-supported attributes and check whether all the required
        parametes have been filled. All missing parameters are set to None
        :param input_data:
        :return:
        """
        return self.clean_input_data(Report, input_data, self.possible_params,
                                     self.required_params, self.complex_params)

    def store(self, autocommit=None):
        if autocommit is None:
            autocommit = self.autocommit
        if autocommit:
            db.session.commit()

    def db_exists(self, report_title):
        """
        If an item with this title already exists, return True. Else, return False.
        :param report_title:
        :return:
        """
        existing_report = Report.query.filter(
            Report.title == report_title).first()
        if existing_report is not None:
            return True
        return False

    def db_create(self, cleaned_data, autocommit=True):
        """
        Create a report. This is a collection of all the write actions to the database, so we can wrap
        them in a transaction. We have to separate the "read" (query) actions as SQLAlchemy commits everything
        before querying (http://docs.sqlalchemy.org/en/latest/orm/session_basics.html).
        :param cleaned_data:
        :param autocommit:
        :return:
        """
        new_report = Report(title=cleaned_data['title'],
                            lang_id=cleaned_data['lang_id'])
        db.session.add(new_report)
        self.store(autocommit)
        return new_report

    def db_update(self, existing_report, cleaned_data, autocommit=True):
        """
        See self.db_create()
        :param existing_report:
        :param cleaned_data:
        :param autocommit:
        :return:
        """
        existing_report = self.update_simple_attributes(
            existing_report,
            simple_attributes=self.simple_params,
            cleaned_data=cleaned_data)
        self.store(autocommit)
        return existing_report

    def questions_by_combined_weight(self, report_id):
        existing_report = self.read(report_id)
        unordered_questions = []
        for section in existing_report.sections:
            for question in section.questions:
                unordered_questions.append({
                    'question_id':
                    question.id,
                    'combined_weight':
                    question.risk_factor.value * question.weight *
                    section.weight,
                    'max_score':
                    scoremodel.modules.api.question.QuestionApi(
                    ).maximum_score(question.id)
                })
        return sorted(unordered_questions,
                      key=lambda q: q['combined_weight'],
                      reverse=True)
コード例 #3
0
class AnswerApi(GenericApi):
    complex_params = []  # These should be a list in input_data
    simple_params = ['answer', 'value', 'lang_id']
    possible_params = ['answer', 'value', 'lang_id']
    required_params = ['answer', 'lang_id']

    def __init__(self, answer_id=None):
        self.answer_id = answer_id
        self.lang_api = LangApi()

    def create(self, input_data):
        """
        Create a new answer from input_data. See QuestionApi.create()
        :param input_data:
        :return:
        """
        cleaned_data = self.parse_input_data(input_data)
        try:
            existing_answer = self.get_answer(cleaned_data['answer'])
        except DatabaseItemDoesNotExist:
            existing_answer = None
        if existing_answer:
            raise DatabaseItemAlreadyExists(_e['item_exists'].format(
                Answer, cleaned_data['answer']))
        new_answer = Answer(answer=cleaned_data['answer'],
                            value=cleaned_data['value'],
                            lang_id=cleaned_data['lang_id'])
        db.session.add(new_answer)
        db.session.commit()
        return new_answer

    def read(self, answer_id):
        """
        Return an answer by its id. See QuestionApi.read()
        :param answer_id:
        :return:
        """
        existing_answer = Answer.query.filter(Answer.id == answer_id).first()
        if existing_answer is None:
            raise DatabaseItemDoesNotExist(_e['item_not_exists'].format(
                Answer, answer_id))
        return existing_answer

    def update(self, answer_id, input_data):
        """
        Update an existing answer. See QuestionApi.update()
        :param answer_id:
        :param input_data:
        :return:
        """
        cleaned_data = self.parse_input_data(input_data)
        existing_answer = self.read(answer_id)
        existing_answer = self.update_simple_attributes(
            existing_answer, self.simple_params, cleaned_data)
        db.session.commit()
        return existing_answer

    def delete(self, answer_id):
        """
        Delete an existing answer. See QuestionApi.delete()
        :param answer_id:
        :return:
        """
        existing_answer = self.read(answer_id)
        db.session.delete(existing_answer)
        db.session.commit()
        return True

    def list(self):
        """
        List all answers
        :return:
        """
        answers = Answer.query.all()
        return answers

    def by_lang(self, lang):
        """
        List all answers in a given language
        :return:
        """
        existing_lang = self.lang_api.by_lang(lang)
        existing_answers = Answer.query.filter(
            Answer.lang_id == existing_lang.id).all()
        return existing_answers

    def parse_input_data(self, input_data):
        cleaned_data = self.clean_input_data(Answer, input_data,
                                             self.possible_params,
                                             self.required_params,
                                             self.complex_params)
        # When updating, optional values that are not present are not automatically assigned their default values
        if 'value' not in cleaned_data or cleaned_data['value'] is None:
            cleaned_data['value'] = 1
        return cleaned_data
コード例 #4
0
class PageApi(GenericApi):
    simple_params = ['menu_link_id', 'content', 'lang_id']
    complex_params = []
    required_params = ['menu_link_id']
    possible_params = simple_params + complex_params

    def __init__(self):
        self.lang_api = LangApi()
        self.menu_link_api = MenuLinkApi()

    def create(self, input_data):
        cleaned_data = self.parse_input_data(input_data)
        if not cleaned_data['lang_id']:
            cleaned_data['lang_id'] = 1
        # Language
        existing_lang = self.lang_api.read(cleaned_data['lang_id'])
        # Menu link
        existing_menu_link = self.menu_link_api.read(cleaned_data['menu_link_id'])
        existing_page = Page.query.filter(and_(Page.menu_link_id == existing_menu_link.id,
                                               Page.lang_id == existing_lang.id)).first()
        # There can not be two pages with the same lang_id and menu_link_id
        if existing_page:
            raise DatabaseItemAlreadyExists(_('A page for menu_link {0} in language {1} already exists.')
                                            .format(cleaned_data['menu_link_id'], cleaned_data['lang_id']))

        new_page = Page(content=cleaned_data['content'])
        new_page.lang = existing_lang
        new_page.menu_link = existing_menu_link
        db.session.add(new_page)
        db.session.commit()
        return new_page

    def read(self, page_id):
        existing_page = Page.query.filter(Page.id == page_id).first()
        if not existing_page:
            raise DatabaseItemDoesNotExist(_e['item_not_exists'].format(Page, page_id))
        return existing_page

    def update(self, page_id, input_data):
        cleaned_data = self.parse_input_data(input_data)
        existing_page = self.read(page_id)
        existing_page.content = cleaned_data['content']
        # Language
        if not cleaned_data['lang_id']:
            cleaned_data['lang_id'] = 1
        existing_lang = self.lang_api.read(cleaned_data['lang_id'])
        # Menu link
        existing_menu_link = self.menu_link_api.read(cleaned_data['menu_link_id'])
        existing_page.lang = existing_lang
        existing_page.menu_link = existing_menu_link
        db.session.commit()
        return existing_page

    def delete(self, page_id):
        existing_page = self.read(page_id)
        db.session.delete(existing_page)
        db.session.commit()
        return True

    def list(self):
        all_pages = Page.query.all()
        return all_pages

    def by_lang(self, lang):
        # Language
        existing_lang = self.lang_api.by_lang(lang)
        return Page.query.filter(Page.lang_id == existing_lang.id).all()

    def by_menu_link(self, menu_link):
        # Menu link
        existing_menu_link = self.menu_link_api.by_menu_link(menu_link)
        return Page.query.filter(Page.menu_link_id == existing_menu_link.id).all()

    def by_menu_link_and_lang(self, menu_link, lang):
        # Language
        existing_lang = self.lang_api.by_lang(lang)
        # Menu link
        existing_menu_link = self.menu_link_api.by_menu_link(menu_link)
        existing_page = Page.query.filter(and_(Page.menu_link_id == existing_menu_link.id,
                                               Page.lang_id == existing_lang.id)).first()
        if not existing_page:
            raise DatabaseItemDoesNotExist(_('A page for menu_link {0} in language {1} does not exist.')
                                           .format(menu_link, lang))
        return existing_page

    def parse_input_data(self, input_data):
        return self.clean_input_data(Page, input_data, possible_params=self.possible_params,
                                     complex_params=self.complex_params,
                                     required_params=self.required_params)
コード例 #5
0
ファイル: document.py プロジェクト: wovari/scoremodel
 def by_lang(self, language):
     lang_api = LangApi()
     db_lang = lang_api.by_lang(language)
     all_documents = Document.query.filter(
         Document.lang_id == db_lang.id).all()
     return all_documents
コード例 #6
0
ファイル: risk_factor.py プロジェクト: wovari/scoremodel
class RiskFactorApi(GenericApi):
    complex_params = []
    simple_params = ['risk_factor', 'value', 'lang_id']
    possible_params = ['risk_factor', 'value', 'lang_id']
    required_params = ['risk_factor', 'lang_id']

    def __init__(self, risk_factor_id=None):
        self.risk_factor_id = risk_factor_id
        self.lang_api = LangApi()

    def create(self, input_data):
        """
        Create a new RiskFactor. See QuestionApi.create(). Fails when the risk factor already exists.
        :param input_data:
        :return:
        """
        cleaned_data = self.parse_input_data(input_data)
        try:
            existing_risk_factor = self.get_risk_factor(
                cleaned_data['risk_factor'])
        except DatabaseItemDoesNotExist:
            existing_risk_factor = None
        if existing_risk_factor:
            raise DatabaseItemAlreadyExists(_e['item_exists'].format(
                RiskFactor, cleaned_data['risk_factor']))
        new_risk_factor = RiskFactor(**cleaned_data)
        db.session.add(new_risk_factor)
        db.session.commit()
        return new_risk_factor

    def read(self, risk_factor_id):
        """
        Return a RiskFactor by its id. See QuestionApi.read()
        :param risk_factor_id:
        :return:
        """
        existing_risk_factor = RiskFactor.query.filter(
            RiskFactor.id == risk_factor_id).first()
        if existing_risk_factor is None:
            raise DatabaseItemDoesNotExist(_e['item_not_exists'].format(
                RiskFactor, risk_factor_id))
        return existing_risk_factor

    def update(self, risk_factor_id, input_data):
        """
        Update an existing RiskFactor. See QuestionApi.update()
        :param risk_factor_id:
        :param input_data:
        :return:
        """
        cleaned_data = self.parse_input_data(input_data)
        existing_risk_factor = self.read(risk_factor_id)
        existing_risk_factor = self.update_simple_attributes(
            existing_risk_factor, self.simple_params, cleaned_data)
        db.session.commit()
        return existing_risk_factor

    def delete(self, risk_factor_id):
        """
        Delete an existing RiskFactor. See QuestionApi.delete()
        :param risk_factor_id:
        :return:
        """
        existing_risk_factor = self.read(risk_factor_id)
        db.session.delete(existing_risk_factor)
        db.session.commit()
        return True

    def list(self):
        """
        List all risk_factors
        :return:
        """
        risk_factors = RiskFactor.query.all()
        return risk_factors

    def by_lang(self, lang):
        """
        List all in a given language
        :return:
        """
        existing_lang = self.lang_api.by_lang(lang)
        existing_reports = RiskFactor.query.filter(
            RiskFactor.lang_id == existing_lang.id).all()
        return existing_reports

    def parse_input_data(self, input_data):
        return self.clean_input_data(RiskFactor, input_data,
                                     self.possible_params,
                                     self.required_params, self.complex_params)