本文整理汇总了Python中snisi_core.models.Entities.Entity类的典型用法代码示例。如果您正苦于以下问题:Python Entity类的具体用法?Python Entity怎么用?Python Entity使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Entity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle
def handle(self, *args, **options):
mali = Entity.get_or_none("mali")
segou = Entity.get_or_none("2732")
mopti = Entity.get_or_none("SSH3")
bamako = Entity.get_or_none("9GR8")
entities = [mali] + \
[e for region in (segou, mopti, bamako)
for e in region.get_health_centers() +
region.get_health_districts()]
cluster = Cluster.get_or_none("epidemiology_routine")
for entity in entities:
if entity is None:
continue
p, created = Participation.objects.get_or_create(
cluster=cluster,
entity=entity,
is_active=True)
if created:
logger.info(p)
# create group
group = Group.get_or_none("smir_alert_response")
if group is None:
group = Group(slug="smir_alert_response",
name="Réponse Alertes SMIR")
group.save()
for username in response_team:
group.members.add(Provider.get_or_none(username))
示例2: handle
def handle(self, *args, **options):
epidemio_cluster = Cluster.objects.get(slug="epidemiology_routine")
DEBUG_change_system_date(
MonthPeriod.from_url_str("07-2012").end_on
- datetime.timedelta(days=5), True)
mali = Entity.get_or_none("mali")
regions = ['2732']
health_units = [mali]
for region_slug in regions:
region = Entity.get_or_none(region_slug)
health_units += [region] + region.get_health_districts() \
+ region.get_health_centers()
for health_unit in health_units:
logger.info(health_unit)
p, created = Participation.objects.get_or_create(
cluster=epidemio_cluster,
entity=health_unit,
modified_on=timezone.now())
DEBUG_change_system_date(None, True)
示例3: natural_children_as_json_view
def natural_children_as_json_view(request,
parent_slug=None,
type_slug=None,
skip_slugs=[],
filter_func=None):
""" generic view to build json results of entities children list """
# define the filter func based on provided parameter
is_filter_compliant = lambda e: filter_func(e) if filter_func else True
if parent_slug == '___':
parent_slug = 'mali'
if type_slug == '__all__':
type_slug = None
parent = Entity.get_or_none(parent_slug)
if parent is None:
children = []
else:
children = parent.get_natural_children(
skip_slugs=['health_area', 'vfq'])
return HttpResponse(json.dumps(
[Entity.get_or_none(e.slug).to_dict()
for e in children if is_filter_compliant(e)]),
content_type='application/json')
示例4: line_data
def line_data(self, all_fields=False):
e = Entity.get_or_none(self.entity.slug)
lines = []
for inp in self.inputs():
if ((not getattr(e, 'has_ureni', False)
and isinstance(self, NutritionStocksR)) and
inp in self.inputs(ureni_only=True)):
if not all_fields:
continue
d = {'label': self.input_str(inp),
'unit': self.unit_str(inp)}
suffixes = ['initial', 'received', 'used', 'lost']
auto_suffixes = ['balance', 'consumed', 'stocked']
for suffix in auto_suffixes + suffixes:
value = getattr(self, '{}_{}'.format(inp, suffix))
slug = '{}_{}'.format(inp, suffix)
if suffix in auto_suffixes:
full_slug = '{}_{}'.format(inp, suffix)
else:
full_slug = 'stocks_{}_{}'.format(inp, suffix)
d[suffix] = value
d[suffix + '_full_slug'] = full_slug
d[suffix + '_slug'] = slug
lines.append(d)
return lines
示例5: get_slug_path_from
def get_slug_path_from(entity, lineage):
''' walk up the lineage to fetch Entity slugs
Ex: {'health_center': "S5C4",
'health_district: "8R92",
'health_region': "2732"} '''
slugs = {}
if entity is None:
return slugs
rlineage = list(reversed(lineage))
for idx, ts in enumerate(rlineage):
if not len(slugs) and ts != entity.type.slug:
continue
if ts == entity.type.slug:
slugs.update({ts: entity.slug})
continue
parent = getattr(
Entity.get_or_none(slugs.get(rlineage[idx - 1])),
'get_{}'.format(ts), lambda: None)()
if parent:
slugs.update({ts: parent.slug})
return slugs
示例6: get_indicator_data
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'))
示例7: get_match
def get_match(snisi_children, dhis):
for child in snisi_children:
if norm(child.name) == norm(dhis['name']):
return child
if dhis['id'] in custom_mapping.keys():
return Entity.get_or_none(custom_mapping[dhis['id']])
return None
示例8: handle
def handle(self, *args, **options):
# set/create the destination folder
report_folder = os.path.join(settings.FILES_REPOSITORY,
"malaria",
"quarter_reports")
mkdir_p(report_folder)
# inputs
year = options.get('year')
quarter_num = options.get('quarter_num')
logger.info("Exporting quarter reports for Q{}-{} to {}"
.format(quarter_num, year, report_folder))
cluster = Cluster.get_or_none("malaria_monthly_routine")
if options.get('entity'):
targets = [Entity.get_or_none(options.get('entity'))]
else:
targets = cluster.members()
for entity in targets:
logger.info(entity)
doc, filename = generate_report(year, quarter_num, entity)
if doc and filename:
filepath = os.path.join(report_folder, filename)
with open(filepath, 'w') as f:
Renderer().Write(doc, f)
logger.info("\tCreated {}".format(filepath))
else:
logger.info("\tNo document for {}".format(entity))
示例9: provider_is_allowed
def provider_is_allowed(provider, slug, location=None):
""" single entry point for provider permission check
permission slugs respects the following format:
<action>_<description>
action in:
* access (read data)
* create-report (create reports)
* download (download reports and files)
* edit-report (modify existing reports)
* validate-report (change validation status)
# * view-map (maps provide overiew on larger locations)
* monitor (for snisi-tech only)
* manage (for snisi-admin only) """
try:
prole, plocation, privileges, action, domain, extension = \
get_permission_request_data(provider, slug, location)
except ValueError:
# request malformed resulting in no access
return False
# admin is god.
if prole == 'snisi_admin':
return True
if location is None:
location = Entity.get_or_none('mali')
else:
location = location.casted()
for domain in Domain.active.all():
allow_func = domain.import_from('permissions.provider_is_allowed')
if allow_func is None:
continue
ret = allow_func(prole=prole,
plocation=plocation,
privileges=privileges,
location=location,
action=action,
domain=domain,
extension=extension)
if ret is None:
continue
return ret
ret = default_permissions(prole=prole,
plocation=plocation,
privileges=privileges,
location=location,
action=action,
domain=domain,
extension=extension)
if ret is not None:
return ret
# default to non-granted
return False
示例10: handle
def handle(self, *args, **options):
mali = Entity.get_or_none("mali")
drmopti = Entity.get_or_none("SSH3")
dsmopti = Entity.get_or_none("HFD9")
dsbandiagara = Entity.get_or_none("MJ86")
cluster = Cluster.get_or_none("malaria_weekly_routine")
for entity in [mali, drmopti, dsmopti, dsbandiagara] + \
dsmopti.get_health_centers() + \
dsbandiagara.get_health_centers():
p, created = Participation.objects.get_or_create(
cluster=cluster,
entity=entity)
logger.info(p)
示例11: indicators_browser
def indicators_browser(request,
entity_slug=None,
perioda_str=None,
periodb_str=None,
indicators={},
context={},
view_name='indicators_browser',
**kwargs):
cluster = Cluster.get_or_none('nutrition_routine')
perm_slug = "access_{}".format(cluster.domain.slug)
root = user_root_for(request.user, perm_slug)
entity = Entity.get_or_none(entity_slug) or root
# make sure requested entity is in cluster
ensure_entity_in_cluster(cluster, entity)
# check permissions on this entity and raise 403
provider_allowed_or_denied(request.user, 'access_nutrition', entity)
# mission browser is reserved to district-level and above
ensure_entity_at_least(entity, 'health_district')
# report_cls depends on entity
try:
report_cls = NutritionR \
if entity.type.slug == 'health_center' else AggNutritionR
except:
report_cls = None
context.update(entity_periods_context(
request=request,
root=root,
cluster=cluster,
view_name=view_name,
entity_slug=entity_slug,
report_cls=report_cls,
perioda_str=perioda_str,
periodb_str=periodb_str,
period_cls=MonthPeriod,
must_be_in_cluster=True,
allow_coming_year=True,
full_lineage=['country', 'health_region', 'health_district'],
))
for indic_slug, indic_cls in indicators.items():
indicators[indic_slug] = indic_cls(entity=entity,
periods=context['periods'])
context.update({indic_slug: indicators[indic_slug]})
context.update({'indicators': indicators})
entities_periods = generate_entities_periods_matrix(
entity=context['entity'], periods=context['periods'])
context.update({'entities_periods': entities_periods})
return render(request,
kwargs.get('template_name', 'nutrition/indicators.html'),
context)
示例12: handle
def handle(self, *args, **options):
october = MonthPeriod.from_url_str("10-2014")
november = MonthPeriod.from_url_str("11-2014")
mopti_csref = Entity.get_or_none("J5C6")
logger.info("Remove Expected and data for {}".format(october))
rc_slugs = ['nutrition_monthly_routine',
'nutrition_monthly_routine_aggregated',
'nut_urenam_monthly_routine',
'nut_urenam_monthly_routine_aggregated',
'nut_urenas_monthly_routine',
'nut_urenas_monthly_routine_aggregated',
'nut_ureni_monthly_routine',
'nut_ureni_monthly_routine_aggregated',
'nut_stocks_monthly_routine',
'nut_stocks_monthly_routine_aggregated',
'nutrition_weekly_routine',
'nutrition_weekly_routine_aggregated']
for rc_slug in rc_slugs:
rc = ReportClass.get_or_none(rc_slug)
logger.info("Deleting expecteds")
ExpectedReporting.objects.filter(
report_class=rc,
period__end_on__lte=october.end_on).delete()
logger.info("Deleting reports and expected validations")
rqs = rc.report_class.objects.filter(
period__end_on__lte=october.end_on)
for r in rqs:
logger.info("\treport: {}".format(r))
if r.expected_reportings.count():
logger.info("\tfound exp")
r.expected_reportings.all().delete()
if r.expected_validation:
logger.info("\tfound expval")
r.expected_validation.delete()
logger.info("\tdeleting report.")
r.delete()
logger.info("Updating Mopti CSRef")
mopti_csref.has_urenam = False
mopti_csref.has_urenas = False
mopti_csref.save()
logger.info("Removing Mopti CSRef Expected")
ExpectedReporting.objects.filter(
entity__slug=mopti_csref.slug,
report_class__slug__in=['nut_urenam_monthly_routine',
'nut_urenam_monthly_routine_aggregated',
'nut_urenas_monthly_routine',
'nut_urenas_monthly_routine_aggregated'],
period=november).delete()
logger.info("done.")
示例13: get_detail
def get_detail(request, entity_slug=None):
""" json results for passed entity """
entity = Entity.get_or_none(entity_slug)
if entity is None:
data = None
else:
data = entity.to_dict()
return JsonResponse(data, safe=False)
示例14: _getChildren
def _getChildren(parent):
qs = Participation.objects.filter(cluster=cluster)
if parent.type.slug == 'health_district':
qs = qs.filter(entity__parent__parent=parent)
else:
qs = qs.filter(entity__parent=parent)
return [Entity.get_or_none(v['entity'])
for v in qs.order_by('entity__name')
.values('entity').distinct()]
示例15: _check
def _check(self, **options):
# district
entity = Entity.get_or_none(self.get('district'),
type_slug='health_district')
if entity is None:
self.add_error("Aucun District ne correspond "
"au code {}".format(self.get('district')),
field='district', blocking=True)
self.set('clean_entity', entity)
# started_on must be <= today
today = datetime.date.today()
try:
self.set('clean_ended_on',
parse_date_string(self.get('ended_on'), as_date=True))
except:
self.add_error("La date de fin de mission est incorrecte: "
"{}.".format(self.get('clean_ended_on')),
blocking=True)
if self.get('clean_ended_on') > today:
self.add_error("La date de fin de mission est dans "
"le futur: {}".format(self.get('clean_ended_on')),
blocking=True, field='ended_on')
open_missions = CATMissionR.objects.filter(
entity=entity,
created_by=self.get('submitter'),
).exclude(completion_status=CATMissionR.COMPLETE)
if not open_missions.count():
self.add_error("Aucune mission cataracte en cours pour vous. "
"Commencez par envoyer le formulaire de "
"début de mission.", blocking=True)
if open_missions.count() > 1:
self.add_error("Vous avez plusieurs missions ouvertes. "
"Merci de contacter ANTIM.", blocking=True)
missionR = open_missions.all()[0]
self.set('missionR', missionR)
if self.get('clean_ended_on') < missionR.started_on:
self.add_error("La date de fin de mission {} est antérieure "
"à la date de début: {}"
.format(self.get('clean_ended_on'),
missionR.started_on),
blocking=True, field='ended_on')
expected_reporting = ExpectedReporting.get_or_none(
report_class=reportcls_mission,
period=missionR.period,
entity=missionR.entity)
self.set('expected_reporting', expected_reporting)