seitime-frappe/frappe/utils/file_lock.py
Gavin D'souza 3446026555 chore: Update header: license.txt => LICENSE
The license.txt file has been replaced with LICENSE for quite a while
now. INAL but it didn't seem accurate to say "hey, checkout license.txt
although there's no such file". Apart from this, there were
inconsistencies in the headers altogether...this change brings
consistency.
2021-09-03 12:02:59 +05:30

46 lines
1,020 B
Python

# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
'''
File based locking utility
'''
import os
from time import time
from frappe.utils import get_site_path, touch_file
class LockTimeoutError(Exception):
pass
def create_lock(name):
'''Creates a file in the /locks folder by the given name'''
lock_path = get_lock_path(name)
if not check_lock(lock_path):
return touch_file(lock_path)
else:
return False
def lock_exists(name):
'''Returns True if lock of the given name exists'''
return os.path.exists(get_lock_path(name))
def check_lock(path, timeout=600):
if not os.path.exists(path):
return False
if time() - os.path.getmtime(path) > timeout:
raise LockTimeoutError(path)
return True
def delete_lock(name):
lock_path = get_lock_path(name)
try:
os.remove(lock_path)
except OSError:
pass
return True
def get_lock_path(name):
name = name.lower()
locks_dir = 'locks'
lock_path = get_site_path(locks_dir, name + '.lock')
return lock_path