Created
April 9, 2021 14:50
-
-
Save baxeico/f2c63ba6a9806150a7445aece5124799 to your computer and use it in GitHub Desktop.
Django command with lockfile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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