Source

django-ipgeobase / django_ipgeobase / management / commands / ipgeobase_update.py

The default branch has multiple heads

Full commit
#encoding:utf8
from django.core.management.base import NoArgsCommand
from django.db import connection, transaction
from django_ipgeobase.conf import *
from zipfile import ZipFile
from urllib import urlopen
from cStringIO import StringIO
from django.core.mail import mail_admins

DELETE_SQL = \
"""
DELETE FROM django_ipgeobase_ipgeobase
"""

INSERT_SQL = \
"""
INSERT INTO django_ipgeobase_ipgeobase
(ip_block, "start", "end", city, region, district, latitude, longitude)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""

ERROR_SUBJECT = u"Ошибка команды ipgeobase_update"
send_message = IPGEOBASE_SEND_MESSAGE_FOR_ERRORS

class Command(NoArgsCommand):
    """С помощью этой команды база с ip-блоками обновляется с сайта-источника"""
    def handle(self, *args, **options):
        print u"Скачиваем zip-архив базы с сайта-источника..."
        f = urlopen(IPGEOBASE_SOURCE_URL)
        buffer = StringIO(f.read())
        f.close()
        print u"Распаковываем..."
        zip_file = ZipFile(buffer)
        try:
            file_read = zip_file.read(IPGEOBASE_FILENAME)
        except KeyError:
            message = u"Файл %s не найден в архиве" % IPGEOBASE_FILENAME
            if send_message:
                mail_admins(subject=ERROR_SUBJECT, message=message)
            return message
        zip_file.close()
        buffer.close()
        print u"Начинаем обновление..."
        lines = file_read.decode(IPGEOBASE_CODING).split('\n')
        cursor = connection.cursor()
        transaction.enter_transaction_management()
        try:
            transaction.managed(True)
            print u"Удаляем старые записи в таблице ipgeobase..."
            cursor.execute(DELETE_SQL)
            print u"Записываем новое..."
            cursor.executemany(INSERT_SQL,
                               [l.split('\t') for l in lines if l.strip()])
            transaction.commit()
        except Exception, e:
            message = u"Данные не обновлены:", e
            if send_message:
                mail_admins(subject=ERROR_SUBJECT, message=message)
            return message
        finally:
            transaction.rollback()
            transaction.leave_transaction_management()
        return u"Таблица ipgeobase обновлена."