Browse Source

Transforma scripts isolados em comandos admin-manage

Scripts isolados ficam separados da aplicação e precisam preparar
o ambiente django, que pode variar em cada ambiente.
Comandos admin podem ser executados dentro do contexto da aplicação
invocando ./manage.py <command>
stable/1.0
Sesostris Vieira 12 years ago
parent
commit
23e545c855
  1. 30
      etc/cron/atualiza_data_uso.py
  2. 21
      etc/cron/cronscript.py
  3. 0
      sigi/apps/metas/management/__init__.py
  4. 0
      sigi/apps/metas/management/commands/__init__.py
  5. 31
      sigi/apps/metas/management/commands/gera_map_data.py
  6. 5
      sigi/apps/metas/views.py
  7. 0
      sigi/apps/servicos/management/__init__.py
  8. 0
      sigi/apps/servicos/management/commands/__init__.py
  9. 35
      sigi/apps/servicos/management/commands/atualiza_uso_servico.py
  10. 20
      sigi/apps/servicos/models.py

30
etc/cron/atualiza_data_uso.py

@ -1,30 +0,0 @@
# -*- coding: utf-8 -*-
# Atualiza a data de último uso dos serviços SEIT realizados pelas Casas Legislativas
# Colocar no CRON - basta executar uma vez por dia
#
import sys
from django.core.management import setup_environ
# Produção
sys.path.insert(0, '/var/interlegis/sigi')
sys.path.insert(0, '/var/interlegis/sigi/sigi')
# Dev
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__) + '../..')
PROJECT_DIR = BASE_DIR + '/sigi'
print BASE_DIR, PROJECT_DIR
sys.path.insert(0, BASE_DIR)
sys.path.insert(0, PROJECT_DIR)
# Faça!
from sigi import settings
setup_environ(settings)
from sigi.apps.servicos.models import Servico
queryset = Servico.objects.exclude(url="").exclude(tipo_servico__string_pesquisa="")
for obj in queryset:
obj.atualiza_data_uso()
print obj.url, obj.data_ultimo_uso, obj.erro_atualizacao

21
etc/cron/cronscript.py

@ -1,21 +0,0 @@
# -*- coding: utf-8 -*-
import sys
from django.core.management import setup_environ
# Produção
sys.path.insert(0, '/var/interlegis/sigi')
sys.path.insert(0, '/var/interlegis/sigi/sigi')
# Dev
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__) + '../../..')
PROJECT_DIR = BASE_DIR + '/sigi'
sys.path.insert(0, BASE_DIR)
sys.path.insert(0, PROJECT_DIR)
# Faça!
from sigi import settings
setup_environ(settings)
from sigi.apps.metas.views import gera_map_data_file
print gera_map_data_file(cronjob=True)

0
sigi/apps/metas/management/__init__.py

0
sigi/apps/metas/management/commands/__init__.py

31
sigi/apps/metas/management/commands/gera_map_data.py

@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
#
# sigi.apps.servicos.management.commands.atualiza_uso_servico
#
# Copyright (c) 2012 by Interlegis
#
# GNU General Public License (GPL)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
from django.core.management.base import BaseCommand
from sigi.apps.metas.views import gera_map_data_file
class Command(BaseCommand):
help = u'Gera arquivo de dados de plotagem do mapa de atuação do Interlegis.'
def handle(self, *args, **options):
result = gera_map_data_file(cronjob=True)
self.stdout.write(result+"\n")

5
sigi/apps/metas/views.py

@ -288,10 +288,9 @@ def gera_map_data_file(cronjob=False):
file = open(JSON_FILE_NAME, 'w')
file.write(json_data)
file.close()
except: # A gravação não foi bem sucedida ...
except Exception as e: # A gravação não foi bem sucedida ...
if cronjob: # ... o chamador deseja a mensagem de erro
import sys
return sys.exc_info()[0]
return str(e)
else:
pass # ... ou os dados poderão ser usados de qualquer forma

0
sigi/apps/servicos/management/__init__.py

0
sigi/apps/servicos/management/commands/__init__.py

35
sigi/apps/servicos/management/commands/atualiza_uso_servico.py

@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
#
# sigi.apps.servicos.management.commands.atualiza_uso_servico
#
# Copyright (c) 2012 by Interlegis
#
# GNU General Public License (GPL)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
from django.core.management.base import BaseCommand
from sigi.apps.servicos.models import Servico
class Command(BaseCommand):
help = u'Atualiza a informação de data de último serviço dos serviços SEIT hospedados no Interlegis.'
def handle(self, *args, **options):
verbosity = int(options['verbosity'])
queryset = Servico.objects.exclude(url="").exclude(tipo_servico__string_pesquisa="")
for obj in queryset:
obj.atualiza_data_uso()
if ((verbosity == 1) and (obj.data_ultimo_uso is None)) or (verbosity > 1):
self.stdout.write(u"%s \t %s \t %s\n" % (obj.url, obj.data_ultimo_uso, obj.erro_atualizacao))

20
sigi/apps/servicos/models.py

@ -52,11 +52,11 @@ class Servico(models.Model):
casa_legislativa.casa_uf_filter = True
def atualiza_data_uso(self):
def reset(erro=u""):
def reset(erro=u"", comment=u""):
if self.data_ultimo_uso is None and not erro:
return
self.data_ultimo_uso = None
self.erro_atualizacao = erro
self.erro_atualizacao = comment + '<br/>' + erro
self.save()
return
@ -77,15 +77,25 @@ class Servico(models.Model):
import urllib2
from xml.dom.minidom import parseString
try:
try: # Captura erros de conexão
try: # Tentar conxão sem proxy
req = urllib2.urlopen(url=url, timeout=5)
except: # Tentar com proxy
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
req = opener.open(fullurl=url, timeout=5)
except Exception as e:
reset(erro=str(e), comment=u'Não foi possível conectar com o servidor. Pode estar fora do ar ou não ser um ' +
self.tipo_servico.nome)
return
try:
rss = req.read()
except Exception as e:
reset(erro=str(e), comment=u'Não foi possível receber os dados do servidor. O acesso pode ter sido negado.')
return
try:
xml = parseString(rss)
items = xml.getElementsByTagName('item')
first_item = items[0]
@ -96,7 +106,9 @@ class Servico(models.Model):
self.erro_atualizacao = ""
self.save()
except Exception as e:
reset(erro=str(e))
reset(erro=str(e), comment=u'A resposta do servidor não é compatível com %s. Pode ser outro software que está sendo usado' %
self.tipo_servico.nome)
return
def __unicode__(self):
return "%s (%s)" % (self.tipo_servico.nome, 'ativo' if self.data_desativacao is None else 'Desativado')

Loading…
Cancel
Save