2008-07-01 23:10:51 +08:00
|
|
|
"""
|
|
|
|
Portable file locking utilities.
|
|
|
|
|
|
|
|
Based partially on example by Jonathan Feignberg <jdf@pobox.com> in the Python
|
|
|
|
Cookbook, licensed under the Python Software License.
|
|
|
|
|
|
|
|
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203
|
|
|
|
|
|
|
|
Example Usage::
|
|
|
|
|
|
|
|
>>> from django.core.files import locks
|
2012-05-05 20:01:38 +08:00
|
|
|
>>> with open('./file', 'wb') as f:
|
2012-05-05 22:54:30 +08:00
|
|
|
... locks.lock(f, locks.LOCK_EX)
|
|
|
|
... f.write('Django')
|
2008-07-01 23:10:51 +08:00
|
|
|
"""
|
|
|
|
|
2013-10-25 01:30:03 +08:00
|
|
|
__all__ = ('LOCK_EX', 'LOCK_SH', 'LOCK_NB', 'lock', 'unlock')
|
2008-07-01 23:10:51 +08:00
|
|
|
|
|
|
|
system_type = None
|
|
|
|
|
|
|
|
try:
|
|
|
|
import win32con
|
|
|
|
import win32file
|
|
|
|
import pywintypes
|
|
|
|
LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
|
|
|
|
LOCK_SH = 0
|
|
|
|
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
|
|
|
|
__overlapped = pywintypes.OVERLAPPED()
|
|
|
|
system_type = 'nt'
|
|
|
|
except (ImportError, AttributeError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
try:
|
|
|
|
import fcntl
|
|
|
|
LOCK_EX = fcntl.LOCK_EX
|
|
|
|
LOCK_SH = fcntl.LOCK_SH
|
|
|
|
LOCK_NB = fcntl.LOCK_NB
|
|
|
|
system_type = 'posix'
|
|
|
|
except (ImportError, AttributeError):
|
|
|
|
pass
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2008-08-12 00:51:18 +08:00
|
|
|
def fd(f):
|
|
|
|
"""Get a filedescriptor from something which could be a file or an fd."""
|
2013-05-27 10:47:50 +08:00
|
|
|
return f.fileno() if hasattr(f, 'fileno') else f
|
2008-08-12 00:51:18 +08:00
|
|
|
|
2008-07-01 23:10:51 +08:00
|
|
|
if system_type == 'nt':
|
|
|
|
def lock(file, flags):
|
2008-08-12 00:51:18 +08:00
|
|
|
hfile = win32file._get_osfhandle(fd(file))
|
2008-07-01 23:10:51 +08:00
|
|
|
win32file.LockFileEx(hfile, flags, 0, -0x10000, __overlapped)
|
|
|
|
|
|
|
|
def unlock(file):
|
2008-08-12 00:51:18 +08:00
|
|
|
hfile = win32file._get_osfhandle(fd(file))
|
2008-07-01 23:10:51 +08:00
|
|
|
win32file.UnlockFileEx(hfile, 0, -0x10000, __overlapped)
|
|
|
|
elif system_type == 'posix':
|
|
|
|
def lock(file, flags):
|
2008-08-29 03:28:45 +08:00
|
|
|
fcntl.lockf(fd(file), flags)
|
2008-07-01 23:10:51 +08:00
|
|
|
|
|
|
|
def unlock(file):
|
2008-08-29 03:28:45 +08:00
|
|
|
fcntl.lockf(fd(file), fcntl.LOCK_UN)
|
2008-07-01 23:10:51 +08:00
|
|
|
else:
|
|
|
|
# File locking is not supported.
|
|
|
|
LOCK_EX = LOCK_SH = LOCK_NB = None
|
|
|
|
|
|
|
|
# Dummy functions that don't do anything.
|
|
|
|
def lock(file, flags):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def unlock(file):
|
|
|
|
pass
|