Skip to content

Instantly share code, notes, and snippets.

@hbruno
Created March 6, 2018 16:18
Show Gist options
  • Save hbruno/bf01b52d6eaf204e6b3e7731668b345a to your computer and use it in GitHub Desktop.
Save hbruno/bf01b52d6eaf204e6b3e7731668b345a to your computer and use it in GitHub Desktop.
Progress and logging django command
from django.core.management.base import BaseCommand
from tqdm import trange
from random import random, randint
from time import sleep
import logging
logger = logging.getLogger('commands') # or __name__
class Command(BaseCommand):
"""
Primero instalar libreria de progress bar con `pip install tqdm`
Configurar en settings LOGGING['commands']
Este comando usa el verbosity para setear el nivel de logueo.
./manage.py text_command -v 2
"""
LEVELS = {
0: logging.ERROR,
1: logging.WARN,
2: logging.INFO,
3: logging.DEBUG
}
help = 'Test logging tools'
def handle(self, *args, **options):
logger.setLevel(self.LEVELS[options['verbosity']])
logger.info('Starting command %s ', __name__)
t = trange(40)
for i in t:
try:
if i % 20 == 0:
raise('Error grave')
# Texto a la izq de la barra de progreso
t.set_description('%d' % i)
# Texto a la der de la barra de progreso
# Los parametros pueden ser cualquier cosa.
t.set_postfix(loss=random(), gen=randint(1, 999), str='h', lst=[1, 2])
logger.debug('Process %i', i)
except:
logger.exception('Ups! Fake Exception.')
sleep(0.1)
logger.info('End command')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment