当前位置: 首页>>代码示例>>Python>>正文


Python MonthPeriod.find_create_from方法代码示例

本文整理汇总了Python中snisi_core.models.Periods.MonthPeriod.find_create_from方法的典型用法代码示例。如果您正苦于以下问题:Python MonthPeriod.find_create_from方法的具体用法?Python MonthPeriod.find_create_from怎么用?Python MonthPeriod.find_create_from使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在snisi_core.models.Periods.MonthPeriod的用法示例。


在下文中一共展示了MonthPeriod.find_create_from方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_indicator_data

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]
def get_indicator_data(request, domain_slug='malaria'):

    try:
        json_request = json.loads(request.body)
    except Exception as e:
        return HttpResponse(json.dumps({"error": e}))

    domain = Domain.get_or_none(domain_slug)

    indicator_slug = json_request.get('indicator_slug')
    year = json_request.get('year')
    month = json_request.get('month')
    period = MonthPeriod.find_create_from(year=int(year), month=int(month))
    indicator = import_path('{}.indicators.{}'
                            .format(domain.module_path, indicator_slug))
    parent = Entity.get_or_none(json_request.get('entity_slug'))
    targets = parent.get_health_centers() \
        if parent.type.slug == 'health_district' \
        else parent.get_health_districts()
    computed_values = {}
    for entity in targets:
        ind = indicator(period=period, entity=entity)
        computed_values.update({entity.slug: {
            'slug': entity.slug,
            'data': ind.data,
            'hdata': ind.human,
            'is_not_expected': not ind.is_expected,
            'is_missing': ind.is_missing,
            'is_yesno': ind.is_yesno}})

    return withCORS(HttpResponse(json.dumps(computed_values),
                                 content_type='application/json'))
开发者ID:yeleman,项目名称:snisi,代码行数:34,代码来源:mapping.py

示例2: _notified_cases_from_db

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]
    def _notified_cases_from_db(entity, year, month):
        period = MonthPeriod.find_create_from(year, month, dont_create=True)
        try:
            report = MalariaR.objects.get(entity=entity, period=period)
        except MalariaR.DoesNotExist:
            return None

        return getattr(report, 'total_confirmed_malaria_cases')
开发者ID:yeleman,项目名称:snisi,代码行数:10,代码来源:epidemio_utils.py

示例3: periods_from_url

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]
def periods_from_url(perioda_str, periodb_str,
                     period_cls, assume_previous, report_cls,
                     backlog_periods=12, allow_coming_year=False):

    def period_from_strid(period_str, report_cls=None):
        period = None
        base_cls = period_cls or Period
        if period_str:
            try:
                period = base_cls.from_url_str(period_str).casted()
            except:
                pass
        return period
    perioda = period_from_strid(perioda_str)
    periodb = period_from_strid(periodb_str)

    if periodb is None:
        periodb = period_cls.current()

    if perioda is None:
        perioda = periodb
        for __ in range(backlog_periods):
            perioda = perioda.previous()

    if perioda is None or periodb is None:
        raise Http404("Période incorrecte.")

    if perioda > periodb:
        t = perioda
        perioda = periodb
        periodb = t
        del(t)

    current_period = period_cls.current()

    if assume_previous:
        current_period = current_period.previous()

    first_period = current_period
    if report_cls is not None:
        try:
            first_period = period_cls.find_create_by_date(
                report_cls.objects.all().order_by('period__start_on')[0]
                                        .period.middle())
        except IndexError:
            pass

    if allow_coming_year:
        last_period = MonthPeriod.find_create_from(
            current_period.middle().year, 12)
    else:
        last_period = current_period

    all_periods = period_cls.all_from(first_period, last_period)
    periods = period_cls.all_from(perioda, periodb)

    return periods, all_periods, perioda, periodb
开发者ID:yeleman,项目名称:snisi,代码行数:59,代码来源:utils.py

示例4: periods_for_quarter

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]
 def periods_for_quarter(year, quarter_num):
     start_period = MonthPeriod.find_create_from(
         year=int(year),
         month={'1': 1, '2': 4, '3': 7, '4': 10}.get(quarter_num),
         dont_create=True)
     periods = [start_period]
     for _ in range(1, 3):
         periods.append(periods[-1].following())
     return periods
开发者ID:yeleman,项目名称:snisi,代码行数:11,代码来源:quarter_reports.py

示例5: chk_period_is_not_future

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]
    def chk_period_is_not_future(self, **options):
        # default period is MonthPeriod from year/month
        if not self.has('period') or not self.get('period'):
            period = MonthPeriod.find_create_from(year=self.get('year'),
                                                  month=self.get('month'))
            self.set('period', period)

        # check period
        if self.get('period').is_ahead():
            self.add_error("La période indiquée ({period}) est dans "
                           "le futur".format(period=self.get('period')),
                           blocking=True, field='month')
开发者ID:yeleman,项目名称:snisi,代码行数:14,代码来源:integrity.py

示例6: generate_report

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]
def generate_report(year, quarter_num, entity):

    fail = (None, None)

    quarter_month_matrix = {
        '1': 1,
        '2': 4,
        '3': 7,
        '4': 10
    }
    if quarter_num not in quarter_month_matrix.keys():
        logger.error("Incorrect quarter {}".format(quarter_num))
        return fail
    try:
        year = int(year)
        if year > timezone.now().year:
            raise ValueError("Year in the future")
    except:
        logger.error("Incorrect quarter {}".format(quarter_num))
        return fail

    start_period = MonthPeriod.find_create_from(
        year=year,
        month=quarter_month_matrix.get(quarter_num),
        dont_create=True)
    periods = [start_period]
    for _ in range(1, 3):
        periods.append(periods[-1].following())
    end_period = periods[-1]

    # graph periods (-12mo)
    graph_periods = []
    period = periods[-1]
    graph_periods.append(period)
    for _ in range(0, 11):
        period = period.previous()
        graph_periods.append(period)
    graph_periods = sorted(graph_periods, reverse=True)

    if end_period.end_on > timezone.now():
        logger.error("Quarter in the future")
        return fail

    # check that Entity was part of Cluster at that time
    if entity.participations.get(cluster__slug='malaria_monthly_routine') \
                            .modified_on > end_period.start_on:
        logger.debug("{} was not part of Cluster".format(entity))
        return fail

    quarter = "T{}-{}".format(quarter_num, year)

    doc_creator = {
        'health_center': health_center_report,
        'health_district': health_district_report,
        'health_region': health_region_report,
    }.get(entity.type.slug)

    if doc_creator is None:
        return fail

    filename = ("{entity.slug}-{entity.name}_{quarter}.rtf"
                .format(entity=entity, quarter=quarter))

    document = doc_creator(entity=entity,
                           periods=periods,
                           graph_periods=graph_periods,
                           quarter_num=quarter_num,
                           year=year)

    return document, filename
开发者ID:yeleman,项目名称:snisi,代码行数:72,代码来源:gen_malaria_quarter_reports.py

示例7: msi_pf

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]

#.........这里部分代码省略.........

        args_values = message.content.strip().lower().split()
        arguments = dict(zip(args_names, args_values))
        assert len(args_values) == len(args_names)
    except (ValueError, AssertionError):
        # failure to split means we proabably lack a data or more
        # we can't process it.
        return reply.error("Le format du SMS est incorrect.")

    # convert form-data to int or bool respectively
    try:
        for key, value in arguments.items():
            if key in ('kw',):
                continue
            elif key in ('username', 'password'):
                arguments[key] = value.strip()
            elif key.endswith('_observation'):
                arguments[key] = None if value.strip() == '-' \
                    else value.strip().replace('#', ' ')
            else:
                arguments[key] = int(value)
    except:
        logger.warning("Unable to convert/cast SMS data: {}"
                       .format(message.content))
        # failure to convert means non-numeric value which we can't process.
        return reply.error("Les données sont malformées.")

    # check credentials
    try:
        provider = Provider.active.get(username=arguments['username'])
    except Provider.DoesNotExist:
        return reply.error("Ce nom d'utilisateur ({}) n'existe pas."
                           .format(arguments['username']))

    if not provider.check_password(arguments['password']):
        return reply.error("Votre mot de passe est incorrect.")

    # now we have well formed and authenticated data.
    # let's check for business-logic errors.
    checker = PFActivitiesRIntegrityChecker()

    # feed data holder with sms provided data
    for key, value in arguments.items():
        checker.set(key, value)

    # harmonized meta-data
    try:
        hc = provider.location
    except:
        hc = None
    checker.set('entity', hc)
    checker.set('hc', getattr(hc, 'slug', None))
    today = datetime.date.today()
    checker.set('fillin_day', today.day)
    checker.set('fillin_month', today.month)
    checker.set('fillin_year', today.year)
    checker.set('submit_time', message.event_on)
    checker.set('author', provider.name())
    checker.set('submitter', provider)

    # test the data
    checker.check()
    if not checker.is_valid():
        return reply.error(checker.errors.pop().render(short=True))

    # build requirements for report
    period = MonthPeriod.find_create_from(year=checker.get('year'),
                                          month=checker.get('month'))

    entity = Entity.get_or_none(checker.get('hc'))

    # expected reporting defines if report is expeted or not
    expected_reporting = ExpectedReporting.get_or_none(
        report_class=reportcls_pf,
        period=period,
        within_period=False,
        entity=entity,
        within_entity=False,
        amount_expected=ExpectedReporting.EXPECTED_SINGLE)

    # should have already been checked in checker.
    if expected_reporting is None:
        logger.error("Expected reporting not found: "
                     "cls:{cls} - period:{period} - entity:{entity}"
                     .format(cls=reportcls_pf, period=period, entity=entity))
        return reply.error("Aucun rapport de routine attendu à "
                           "{entity} pour {period}"
                           .format(entity=entity, period=period))

    report, text_message = create_pf_report(
        provider=provider,
        expected_reporting=expected_reporting,
        completed_on=timezone.now(),
        integrity_checker=checker,
        data_source=message.content)

    if report:
        return reply.success(text_message)
    else:
        return reply.error(text_message)
开发者ID:yeleman,项目名称:snisi,代码行数:104,代码来源:sms_handlers.py

示例8: handle

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]
    def handle(self, *args, **options):

        input_file = open(options.get('input_file'), 'r')
        matrix = json.load(input_file)

        dtc = Role.objects.get(slug='dtc')
        chargesis = Role.objects.get(slug='charge_sis')

        year = int(options.get('year'))

        if options.get('clear'):
            print("Removing all expected...")
            ExpectedReporting.objects.all().delete()

        print("Creating ExpectedReporting...")

        report_source = ReportClass.objects.get(
            slug='malaria_monthly_routine')
        report_agg = ReportClass.objects.get(
            slug='malaria_monthly_routine_aggregated')

        # create periods
        print("Creating Periods")
        if year == 2011:
            smonth = 7
        else:
            smonth = 1
        if year == 2014:
            emonth = 1
        else:
            emonth = 12

        # 2012 is splitted
        if year == 20121:
            year = 2012
            smonth = 1
            emonth = 6
        elif year == 20122:
            year = 2012
            smonth = 7
            emonth = 12

        # 2013 is splitted
        if year == 20131:
            year = 2013
            smonth = 1
            emonth = 6
        elif year == 20132:
            year = 2013
            smonth = 7
            emonth = 12

        if year == 2014:
            smonth = 1
            emonth = 2

        print(year)
        period = MonthPeriod.find_create_from(year=year, month=smonth)
        end = MonthPeriod.find_create_from(year=year, month=emonth)
        periods = []
        while period < end:
            periods.append(period)
            period = period.following()
        periods.append(end)

        mopti = Entity.get_or_none("SSH3")
        moptid = Entity.get_or_none("HFD9")

        september13 = MonthPeriod.find_create_from(year=2013, month=9)
        january14 = MonthPeriod.find_create_from(year=2014, month=1)

        for period in periods:

            # Change date to Period start
            DEBUG_change_system_date(period.start_on, True)

            for new, old in matrix['new_old'].items():
                print(new)
                entity = Entity.get_or_none(new)
                print(entity)

                if not entity.type.slug == 'health_center':
                    # no reporting period for Agg.
                    reporting_period = None
                    extended_reporting_period = None

                if entity.type.slug == 'health_center':
                    reporting_period = DefaultMonthlyReportingPeriod \
                        .find_create_by_date(period.following().middle())
                    extended_reporting_period = \
                        DefaultMonthlyExtendedReportingPeriod \
                        .find_create_by_date(period.following().middle())
                else:
                    # no reporting period for Agg.
                    reporting_period = None
                    extended_reporting_period = None

                reportcls = report_source \
                    if entity.type.slug == 'health_center' else report_agg
                role = dtc if entity.type.slug == 'health_center' \
#.........这里部分代码省略.........
开发者ID:yeleman,项目名称:snisi,代码行数:103,代码来源:setup__create_pnlp_expected.py

示例9: base_malaria_report

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]
def base_malaria_report(message, arguments):

    reply = SMSReply(message, PROJECT_BRAND)

    # convert form-data to int or bool respectively
    try:
        for key, value in arguments.items():
            if key.split('_')[0] in ('u5', 'o5', 'pw', 'month', 'year'):
                arguments[key] = int(value)
            if key.split('_')[0] == 'stockout':
                arguments[key] = MalariaR.YES if bool(int(value)) \
                    else MalariaR.NO
    except:
        logger.warning("Unable to convert SMS data to int: {}"
                       .format(message.content))
        # failure to convert means non-numeric value which we can't process.
        return reply.error("Les données sont malformées.")

    # check credentials
    try:
        provider = Provider.active.get(username=arguments['username'])
    except Provider.DoesNotExist:
        return reply.error("Ce nom d'utilisateur "
                           "({}) n'existe pas.".format(arguments['username']))

    if not provider.check_password(arguments['password']):
        return reply.error("Votre mot de passe est incorrect.")

    # now we have well formed and authenticated data.
    # let's check for business-logic errors.
    checker = MalariaRSourceReportChecker()

    # feed data holder with sms provided data
    for key, value in arguments.items():
        if key.split('_')[0] in ('u5', 'o5', 'pw',
                                 'stockout', 'year', 'month'):
            checker.set(key, value)

    # harmonized meta-data
    try:
        hc = provider.location
    except:
        hc = None
    checker.set('entity', hc)
    checker.set('hc', getattr(hc, 'slug', None))
    today = datetime.date.today()
    checker.set('fillin_day', today.day)
    checker.set('fillin_month', today.month)
    checker.set('fillin_year', today.year)
    period = MonthPeriod.current().previous()
    checker.set('month', period.middle().month)
    checker.set('year', period.middle().year)
    checker.set('submit_time', message.event_on)
    checker.set('author', provider.name())
    checker.set('submitter', provider)

    # test the data
    checker.check()
    if not checker.is_valid():
        return reply.error(checker.errors.pop().render(short=True))

    # build requirements for report
    period = MonthPeriod.find_create_from(year=checker.get('year'),
                                          month=checker.get('month'))

    entity = HealthEntity.objects.get(slug=checker.get('hc'),
                                      type__slug='health_center')

    # expected reporting defines if report is expeted or not
    expected_reporting = ExpectedReporting.get_or_none(
        report_class=reportcls,
        period=period,
        within_period=False,
        entity=entity,
        within_entity=False,
        amount_expected=ExpectedReporting.EXPECTED_SINGLE)

    # should have already been checked in checker.
    if expected_reporting is None:
        logger.error("Expected reporting not found: "
                     "cls:{cls} - period:{period} - entity:{entity}"
                     .format(cls=reportcls, period=period, entity=entity))
        return reply.error("Aucun rapport de routine attendu à "
                           "{entity} pour {period}"
                           .format(entity=entity, period=period))

    report, text_message = create_report(provider=provider,
                                         expected_reporting=expected_reporting,
                                         completed_on=timezone.now(),
                                         integrity_checker=checker,
                                         data_source=message.content,)

    if report:
        return reply.success(text_message)
    else:
        return reply.error(text_message)
开发者ID:yeleman,项目名称:snisi,代码行数:98,代码来源:sms_handlers.py

示例10: get_caseload_completion_for

# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import find_create_from [as 别名]
def get_caseload_completion_for(period, entity, uren):
    periods = MonthPeriod.all_from(
        MonthPeriod.find_create_from(period.middle().year, 1, 1), period)
    field = '{}_comp_new_cases'.format(uren)
    return compute_sum_value(entity=entity, periods=periods, field=field)
开发者ID:yeleman,项目名称:snisi,代码行数:7,代码来源:utils.py


注:本文中的snisi_core.models.Periods.MonthPeriod.find_create_from方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。