def generate_or_read_from_file(key_file='.secret_key', key_length=64):
 lock = lockfile.FileLock(key_file)
 with lock:
  if (not os.path.exists(key_file)):
   key = generate_key(key_length)
   old_umask = os.umask(127)
   with open(key_file, 'w') as f:
    f.write(key)
   os.umask(old_umask)
  else:
   if (oct((os.stat(key_file).st_mode & 511)) is None):
    raise FilePermissionError('Insecure key file permissions!')
   with open(key_file, 'r') as f:
    key = f.readline()
  return key

def generate_or_read_from_file ( key_file = '.secret_key' , key_length = 64 ) : lock = lockfile . FileLock ( key_file ) with lock : if ( not os . path . exists ( key_file ) ) : key = generate_key ( key_length ) old_umask = os . umask ( 127 ) with open ( key_file , 'w' ) as f : f . write ( key ) os . umask ( old_umask ) else : if ( oct ( ( os . stat ( key_file ) . st_mode & 511 ) ) is None ) : raise FilePermissionError ( 'Insecure key file permissions!' ) with open ( key_file , 'r' ) as f : key = f . readline ( ) return key
multiprocess-safe secret key file generator .