web/hdalab/management/commands/fill_country_codes.py
author veltr
Thu, 23 Feb 2012 19:45:00 +0100
changeset 123 94fc5f5b5cfd
parent 119 e3ebe3545f72
permissions -rw-r--r--
Added Insee Codes

# -*- coding: utf-8 -*-
'''
Created on Jan 29, 2012

@author: ymh
'''
from django.core.management.base import NoArgsCommand
from django.core.management.color import no_style
import urllib
from hdabo.utils import show_progress
import re
from hdalab.models import CountryCode

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        self.style = no_style()
        
        
        f = urllib.urlopen("http://fr.wikipedia.org/wiki/ISO_3166-1?action=raw&section=3")
        lines = f.read().split("|-")
        
        total = len(lines)
        writer = None
        
        for i,line in enumerate(lines):
            writer = show_progress(i+1, total, line.decode("utf-8"), 50, writer)
            isocode = re.findall("(?m)(\[\[|\|)([A-Z]{3})]]", line)
            countryname = re.findall("(?m)\{\{([^|}]+)", line)
            if len(isocode) and len(countryname):
                isocode = isocode[0][1]
                countryname = countryname[0].strip()
                CountryCode.objects.get_or_create(label=countryname, isocode=isocode)