loadCountries.py 1.88 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
from os.path import abspath, join
Florent Chehab's avatar
Florent Chehab committed
2

Florent Chehab's avatar
Florent Chehab committed
3
import pandas as pd
Florent Chehab's avatar
Florent Chehab committed
4
from backend_app.load_data import ASSETS_PATH
Florent Chehab's avatar
Florent Chehab committed
5
from backend_app.models.country import Country
Florent Chehab's avatar
Florent Chehab committed
6
from base_app.models import User
Florent Chehab's avatar
Florent Chehab committed
7

Florent Chehab's avatar
Florent Chehab committed
8 9 10 11
from .loadGeneric import LoadGeneric


class LoadCountries(LoadGeneric):
Florent Chehab's avatar
Florent Chehab committed
12 13 14 15 16
    """
        Class to handle the loading of countries in the app
    """

    def __init__(self, admin: User):
Florent Chehab's avatar
Florent Chehab committed
17 18 19
        self.admin = admin

    def load(self):
Florent Chehab's avatar
Florent Chehab committed
20 21
        country_file_loc = abspath(join(ASSETS_PATH, "country.csv"))
        conv_alpha_file_loc = abspath(join(ASSETS_PATH, "alpha-conv-table.csv"))
Florent Chehab's avatar
Florent Chehab committed
22

23 24 25
        country_pd = pd.read_csv(
            country_file_loc, sep=",", header=0, dtype=object
        ).fillna("")
Florent Chehab's avatar
Florent Chehab committed
26 27 28

        # Need to load the information for converting
        # Countries alpha-3 code to alpha-2 code
29
        data_conv = pd.read_csv(conv_alpha_file_loc, sep=",", header=0, na_filter=False)
Florent Chehab's avatar
Florent Chehab committed
30 31 32 33 34
        conv_alpha = {}
        for index, row in data_conv.iterrows():
            conv_alpha[row["alpha-3"]] = row["alpha-2"]

        for index, r in country_pd.iterrows():
35
            Iso_3 = str(r["ISO-alpha3 Code"])
Florent Chehab's avatar
Florent Chehab committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
            code_alpha_2 = None
            if Iso_3 in conv_alpha.keys():
                code_alpha_2 = conv_alpha[Iso_3]
            else:
                print("ignoring country :", Iso_3)
                continue

            country = Country(
                name=r["Country or Area"],
                iso_alpha2_code=code_alpha_2,
                iso_alpha3_code=Iso_3,
                region_name=r["Region Name"],
                region_un_code=r["Region Code"],
                sub_region_name=r["Sub-region Name"],
                sub_region_un_code=r["Sub-region Code"],
                intermediate_region_name=r["Intermediate Region Name"],
                intermediate_region_un_code=r["Intermediate Region Code"],
            )
            country.save()
55
            self.add_info_and_save(country, self.admin)