Skip to content

Instantly share code, notes, and snippets.

@baxeico
Created April 9, 2021 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baxeico/f2c63ba6a9806150a7445aece5124799 to your computer and use it in GitHub Desktop.
Save baxeico/f2c63ba6a9806150a7445aece5124799 to your computer and use it in GitHub Desktop.
Django command with lockfile
import logging
from os.path import exists
from os import remove, getpid
from django.core.management.base import BaseCommand
logger = logging.getLogger(__name__)
class LockedCommand(BaseCommand):
"""
A base class for Django commands that shouldn't run concurrently.
Your command should inherit from LockedCommand and implement a locked_handle method.
"""
def add_arguments(self, parser):
parser.add_argument('lockfile')
def handle(self, *args, **options):
pid = str(getpid())
logger.debug('Starting with pid %s' % pid)
lockfile = options['lockfile']
if exists(lockfile):
with open(lockfile, 'r') as fin:
oldpid = fin.read().strip()
logger.debug('Lock file %s exists for PID %s, exiting!' % (lockfile, oldpid))
return
with open(lockfile, 'w') as fout:
fout.write(pid)
try:
self.locked_handle(*args, **options)
except Exception:
logger.exception('Unexpected error in locked command')
finally:
if exists(lockfile):
remove(lockfile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment