22import xmltodict
33from django .conf import settings
44from django .core .management .base import BaseCommand
5+ from django .db import transaction
56from requests .auth import HTTPBasicAuth
7+ from sentry_sdk .crons import monitor
68
79from api .logger import logger
810from api .models import Country , CountryDirectory , CronJob , CronJobStatus
11+ from main .sentry import SentryMonitor
912
1013
1114class Command (BaseCommand ):
1215 help = "Add ns contact details"
1316
17+ @monitor (monitor_slug = SentryMonitor .INGEST_NS_DIRECTORY )
18+ @transaction .atomic
1419 def handle (self , * args , ** kwargs ):
20+ def postprocessor (path , key , value ):
21+ if key == "@i:nil" :
22+ return None
23+ return key , value
24+
1525 logger .info ("Starting NS Contacts" )
1626 url = "https://go-api.ifrc.org/"
1727 headers = {"accept" : "application/xml;q=0.9, */*;q=0.8" }
@@ -33,7 +43,8 @@ def handle(self, *args, **kwargs):
3343 raise Exception ("Error querying NationalSocietiesContacts" )
3444
3545 added = 0
36- dict_data = xmltodict .parse (response .content )
46+ created_country_directory_ids = []
47+ dict_data = xmltodict .parse (response .content , postprocessor = postprocessor )
3748 for data in dict_data ["ArrayOfNationalSocietiesContacts" ]["NationalSocietiesContacts" ]:
3849 country_name = data ["CON_country" ] if isinstance (data ["CON_country" ], str ) else None
3950 if country_name is not None :
@@ -54,7 +65,15 @@ def handle(self, *args, **kwargs):
5465 "position" : data ["CON_title" ],
5566 "country" : country ,
5667 }
57- CountryDirectory .objects .create (** data )
68+ country_directory , _ = CountryDirectory .objects .get_or_create (
69+ country = country ,
70+ first_name__iexact = data ["first_name" ],
71+ last_name__iexact = data ["last_name" ],
72+ position__iexact = data ["position" ],
73+ )
74+ created_country_directory_ids .append (country_directory .pk )
75+ # NOTE: Deleting the country directory which are not available in the source
76+ CountryDirectory .objects .exclude (id__in = created_country_directory_ids ).delete ()
5877 text_to_log = "%s Ns Directory added" % added
5978 logger .info (text_to_log )
6079 body = {"name" : "ingest_ns_directory" , "message" : text_to_log , "num_result" : added , "status" : CronJobStatus .SUCCESSFUL }
0 commit comments