11import logging
22import operator
33import re
4+ import typing
45from functools import reduce
56
67import pandas as pd
1415logger = logging .getLogger (__name__ )
1516
1617
18+ class RollBackException (Exception ):
19+ pass
20+
21+
1722class CountryPlanImporter :
1823 CSV_COLUMN = [
1924 "ISO3" ,
@@ -124,15 +129,11 @@ def _save_country_plan(cls, row):
124129 )
125130
126131 @classmethod
127- def process (cls , file ):
128- data = pd .read_excel (file , skiprows = 4 , na_filter = False , usecols = cls .CSV_COLUMN )
129- data = data [:- 1 ]
130-
132+ def _process (cls , data ) -> typing .List [typing .Dict ]:
131133 errors = []
132134 for row in data .itertuples ():
133135 try :
134- with transaction .atomic ():
135- cls ._save_country_plan (row )
136+ cls ._save_country_plan (row )
136137 except Exception as e :
137138 logger .error (f"Failed to import Country-Plan: iso3:{ row .ISO3 } " , exc_info = True )
138139 errors .append (
@@ -143,6 +144,32 @@ def process(cls, file):
143144 )
144145 return errors
145146
147+ @classmethod
148+ def process (cls , file ) -> typing .List [typing .Dict ]:
149+ data = pd .read_excel (file , skiprows = 4 , na_filter = False , usecols = cls .CSV_COLUMN )
150+ data = data [:- 1 ]
151+ errors = []
152+
153+ try :
154+ with transaction .atomic ():
155+ # Clean-up existing dataset StrategicPriority,MembershipCoordination
156+ StrategicPriority .objects .all ().delete ()
157+ MembershipCoordination .objects .all ().delete ()
158+
159+ # Add new data
160+ errors = cls ._process (data )
161+ if errors :
162+ raise RollBackException ()
163+ except Exception as e :
164+ # handle custom rollback error manually
165+ if not isinstance (e , RollBackException ):
166+ logger .error ("Failed to process Country-Plan" , exc_info = True )
167+ errors .append (dict (error = str (e )))
168+ pass
169+
170+ # Return errors
171+ return errors
172+
146173
147174@shared_task
148175def process_data_import (pk ):
0 commit comments