77 lines
2.8 KiB
Python
77 lines
2.8 KiB
Python
# encoding: utf-8
|
|
|
|
from flask import current_app, g, request, redirect, url_for
|
|
from flask_admin import BaseView, expose
|
|
from slugify import slugify
|
|
|
|
from app.form.admin import ImportForm
|
|
from app.controller.admin.importer import default_import
|
|
from app.model.country import CountryModel
|
|
|
|
|
|
class ImportCountryView(BaseView):
|
|
@expose("/", methods=["GET", "POST"])
|
|
def index(self):
|
|
g.what = {
|
|
"title": "Import countries",
|
|
"description": "Importing countries will add unknown ones and update"
|
|
" known ones. If a country is not present in imported file it"
|
|
" will not be deleted.",
|
|
"endpoint": "countries.index",
|
|
"formats": [
|
|
"File format accepted is CSV (Comma Separated Values).",
|
|
"First line represents column headers.",
|
|
"Other lines are values:",
|
|
"One column MUST be 'name'",
|
|
"One column COULD be 'alpha_2'",
|
|
"One column COULD be 'alpha_3'",
|
|
"One column COULD be 'official_name'",
|
|
],
|
|
"examples": [
|
|
"name,alpha_2",
|
|
"Spain,es",
|
|
"Germany,DE",
|
|
],
|
|
}
|
|
headers = {
|
|
"name": None,
|
|
"alpha_2": "optional",
|
|
"alpha_3": "optional",
|
|
"official_name": "optional",
|
|
}
|
|
reader = default_import(headers)
|
|
if len(g.errors) == 0 and reader is not None:
|
|
for row in reader:
|
|
country = CountryModel.query.filter_by(
|
|
name=row[headers["name"]],
|
|
).first()
|
|
if headers["alpha_2"] is not None:
|
|
alpha_2 = row[headers["alpha_2"]]
|
|
else:
|
|
alpha_2 = None
|
|
if headers["alpha_3"] is not None:
|
|
alpha_3 = row[headers["alpha_3"]]
|
|
else:
|
|
alpha_3 = None
|
|
if headers["official_name"] is not None:
|
|
official_name = row[headers["official_name"]]
|
|
else:
|
|
official_name = None
|
|
if country is None:
|
|
country = CountryModel(
|
|
name = row[headers["name"]],
|
|
slug = slugify(row[headers["name"]]),
|
|
alpha_2 = alpha_2,
|
|
alpha_3 = alpha_3,
|
|
official_state_name = official_name,
|
|
)
|
|
g.messages.append(
|
|
f"{row[headers['name']]} added."
|
|
)
|
|
country.save()
|
|
else:
|
|
# Mise à jour du pays !
|
|
pass
|
|
|
|
return self.render("admin/import.html")
|