Skip to content

Commit d9bbb0c

Browse files
Merge pull request #2182 from IFRCGo/feature/country-plan-import-clean-up
Clean-up StrategicPriority & MembershipCoordination on import
2 parents 00c10fe + fe06502 commit d9bbb0c

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

country_plan/tasks.py

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import logging
22
import operator
33
import re
4+
import typing
45
from functools import reduce
56

67
import pandas as pd
@@ -14,6 +15,10 @@
1415
logger = logging.getLogger(__name__)
1516

1617

18+
class RollBackException(Exception):
19+
pass
20+
21+
1722
class 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
148175
def process_data_import(pk):

0 commit comments

Comments
 (0)