Skip to content

Instantly share code, notes, and snippets.

@hgdeoro
Created June 29, 2013 02:11
Show Gist options
  • Save hgdeoro/5889378 to your computer and use it in GitHub Desktop.
Save hgdeoro/5889378 to your computer and use it in GitHub Desktop.
Comando para Django que chequea lock
import logging
import fcntl
import os
from optparse import make_option
from django.core.management.base import BaseCommand
logger = logging.getLogger(__name__)
#
# Recordar cambiar >> default='/tmp/.some_file.lock'
#
class Command(BaseCommand):
help = "Mensaje de ayuda"
option_list = BaseCommand.option_list + (
make_option('--lock', action='store', dest='lock_file',
default='/tmp/.some_file.lock',
help='Archivo a usar para lock'),
)
def realizar_trabajo():
raise(Exception("IMPLEMENTAR!"))
def handle(self, *args, **options):
lock_file = options.get('lock_file')
FORMAT = "%(asctime)s [{0}] [%(levelname)-5s] %(name)s - %(message)s".format(os.getpid())
if 'DEBUG' in os.environ:
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
else:
logging.basicConfig(format=FORMAT, level=logging.INFO)
if not os.path.exists(lock_file):
open(lock_file, 'a')
logger.info("Intentando obtener lock...")
opened_lock_file = open(lock_file, 'a')
try:
fcntl.lockf(opened_lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
opened_lock_file.seek(0)
opened_lock_file.truncate()
opened_lock_file.write(str(os.getpid()))
opened_lock_file.flush()
except IOError:
try:
locked_by = open(lock_file, 'r').read()
except:
locked_by = '?'
self.stderr.write(
self.style.ERROR("No se pudo obtener lock: {0} - "
"Archivo de LOCK contiene: '{1}'\n".format(lock_file, locked_by))
)
return
logger.info("... lock obtenido!")
from django.db import transaction
logger.info("Iniciando procesamiento...")
realizar_trabajo()
logger.info("Committing...")
transaction.commit_unless_managed()
logger.info("FIN")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment