Code optimization

master
Самоукин Алексей 14 years ago
parent 98a84ede6e
commit 30c95e518a

@ -2375,6 +2375,33 @@ class profile(_file, _terms, xmlShare, processingTemplates):
self.dictTemplates = {}
# Общее количество шаблонов
self.allTemplates = 0
# Аттрибуты для функции шаблона ini()
# Первоначальный словарь переменных для ini()
self.prevDictIni = {}
# Текущий словарь переменных для ini()
self.currDictIni = {}
# Время модификации конфигурационного файла для ini()
self.timeIni = -1
self.uid, self.gid, self.homeDir = self.getDataUser()
def getDataUser(self):
"""Получить информацию о пользователе"""
userName = self.objVar.Get("ur_login")
if not userName:
userName = "root"
import pwd
try:
pwdObj = pwd.getpwnam(userName)
uid = pwdObj.pw_uid
gid = pwdObj.pw_gid
homeDir = pwdObj.pw_dir
except:
print _("error in profile %s")%nameProfile
print _("error profile term %s")%str(funTxt)
print _("Can not found user %s")%str(userName)
cl_base.exit(1)
return uid, gid, homeDir
# Преобразование восьмеричного в целое (ввод строка, вывод число)
def __octToInt(self, strOct):
@ -2616,11 +2643,9 @@ class profile(_file, _terms, xmlShare, processingTemplates):
fileName = terms[0].strip()
# Если домашняя директория
if fileName[0] == "~":
# Получаем информацию о пользователе
uid, gid, homeDir = getDataUser()
# Получаем директорию пользователя
fileName = os.path.join(homeDir, fileName.partition("/")[2],
"")[:-1]
fileName = os.path.join(self.homeDir,
fileName.partition("/")[2],"")[:-1]
elif fileName[0] != "/":
path = os.path.split(nameSystemFile)[0]
fileName=os.path.join(path,fileName)
@ -2628,11 +2653,9 @@ class profile(_file, _terms, xmlShare, processingTemplates):
fileName = terms[1].strip()
# Если домашняя директория
if fileName[0] == "~":
# Получаем информацию о пользователе
uid, gid, homeDir = getDataUser()
# Получаем директорию пользователя
fileName = os.path.join(homeDir, fileName.partition("/")[2],
"")[:-1]
fileName = os.path.join(self.homeDir,
fileName.partition("/")[2],"")[:-1]
elif fileName[1] != "/":
path = os.path.split(nameSystemFile)[0]
fileName=os.path.join(path,fileName)
@ -2862,11 +2885,12 @@ class profile(_file, _terms, xmlShare, processingTemplates):
textProfileTmp[resS.end():]
return textProfileTmp
def loadVarsIni(iniFileName, localVarsIni, isLoadVarsIni):
def loadVarsIni(iniFileName):
""" Читает файл fileName
создает и заполняет переменные на основе этого файла
Используеться совместно c funcIni
"""
localVarsIni = {}
# Выходим если есть предыдущие ошибки
if self.getError():
return False
@ -2878,8 +2902,7 @@ class profile(_file, _terms, xmlShare, processingTemplates):
if self.getError():
# Очистка ошибки
_error.error = []
isLoadVarsIni = False
return isLoadVarsIni
return localVarsIni
# Заполняем переменные для funcIni
for sect in allsect:
sectVars = config.getAreaVars(sect)
@ -2887,49 +2910,33 @@ class profile(_file, _terms, xmlShare, processingTemplates):
nameVar = "%s.%s"%(sect,name)
valueVar = sectVars[name]
localVarsIni[nameVar] = valueVar
if localVarsIni:
isLoadVarsIni = True
else:
isLoadVarsIni = False
return isLoadVarsIni
return localVarsIni
def getDataUser():
"""Получить информацию о пользователе"""
userName = self.objVar.Get("ur_login")
if not userName:
print _("error in profile %s")%nameProfile
print _("error profile term %s")%str(funTxt)
print _("template variable 'ur_login' is empty")
cl_base.exit(1)
import pwd
def getTimeFile(fileName):
# Получаем время модификации файла
try:
pwdObj = pwd.getpwnam(userName)
uid = pwdObj.pw_uid
gid = pwdObj.pw_gid
homeDir = pwdObj.pw_dir
stInfo = os.lstat(fileName)
statInfo = stInfo[stat.ST_MODE]
except:
print _("error in profile %s")%nameProfile
print _("error profile term %s")%str(funTxt)
print _("Can not found user %s")%str(userName)
cl_base.exit(1)
return uid, gid, homeDir
def funcIni(funTxt,resS,localVarsIni,isLoadVarsIni, uid, gid, homeDir,
textProfileTmp):
return 0
# Проверяем существование файла
if stat.S_ISREG(statInfo):
# Получаем метку времени конфигурационного файла
return stInfo[stat.ST_CTIME]
return 0
def funcIni(funTxt, resS, textProfileTmp):
"""локальная функция записывает и считывает значение переменной
из ini файла ~./calculate/ini.env
"""
# ~/.calculate
if not homeDir:
# Получаем информацию о пользователе
uid, gid, homeDir = getDataUser()
pathConfig = os.path.join(homeDir, ".calculate")
pathConfig = os.path.join(self.homeDir, ".calculate")
fileConfig = os.path.join(pathConfig,"ini.env")
# Создаем директорию
if not os.path.exists(pathConfig):
os.makedirs(pathConfig)
os.chown(pathConfig, int(uid), int(gid))
os.chown(pathConfig, int(self.uid), int(self.gid))
termsRaw = funTxt[4:-1].split(",")
flagFirst = True
terms = []
@ -2958,39 +2965,32 @@ class profile(_file, _terms, xmlShare, processingTemplates):
print _("error profile term %s")%str(funTxt)
cl_base.exit(1)
replace = ""
# Получаем время модификации конфигурационного файла
curTime = getTimeFile(fileConfig)
if len(terms) == 1:
if isLoadVarsIni is None:
if self.timeIni != curTime:
# читаем переменные из файла
isLoadVarsIni = loadVarsIni(fileConfig, localVarsIni,
isLoadVarsIni)
if nameLocVar in localVarsIni.keys():
replace = localVarsIni[nameLocVar]
self.prevDictIni = loadVarsIni(fileConfig)
self.currDictIni.update(self.prevDictIni)
self.timeIni = getTimeFile(fileConfig)
if nameLocVar in self.currDictIni.keys():
replace = self.currDictIni[nameLocVar]
elif len(terms) == 2:
if isLoadVarsIni is None:
if self.timeIni != curTime:
# читаем переменные из файла
isLoadVarsIni = loadVarsIni(fileConfig, localVarsIni,
isLoadVarsIni)
self.prevDictIni = loadVarsIni(fileConfig)
self.currDictIni.update(self.prevDictIni)
self.timeIni = getTimeFile(fileConfig)
# Значение локальной переменной
valueLocVar = terms[1]
localVarsIni[nameLocVar] = valueLocVar
self.currDictIni[nameLocVar] = valueLocVar
else:
print _("error in profile %s")%nameProfile
print _("error profile term %s")%str(funTxt)
cl_base.exit(1)
textProfileTmp = textProfileTmp[:resS.start()] + replace +\
textProfileTmp[resS.end():]
return (isLoadVarsIni, uid, gid, homeDir, textProfileTmp)
# Локальные переменные для ini файла
localVarsIni = {}
# Был ли прочитан ini файл
isLoadVarsIni = None
# uid пользователя
uid = ""
# gid пользователя
gid = ""
# Путь к домашней директории пользователя
homeDir = ""
return (textProfileTmp)
# Локальные переменные
localVars = {}
@ -3027,47 +3027,47 @@ class profile(_file, _terms, xmlShare, processingTemplates):
textProfileTmp = funcPush(funTxt,resS,localVars,textProfileTmp)
resS = self._reFunc.search(textProfileTmp)
elif funTxt[:4] == "ini(":
isLoadVarsIni, uid, gid, homeDir, textProfileTmp = funcIni(\
funTxt, resS,
localVarsIni,
isLoadVarsIni,
uid,
gid,
homeDir,
textProfileTmp)
textProfileTmp = funcIni(funTxt, resS, textProfileTmp)
resS = self._reFunc.search(textProfileTmp)
else:
resS = False
if not isLoadVarsIni is None and localVarsIni and homeDir:
pathConfig = os.path.join(self.homeDir,".calculate","ini.env")
if self.prevDictIni != self.currDictIni or\
(self.timeIni!=-1 and getTimeFile(pathConfig)!= self.timeIni):
# Записываем переменные в конфигурационный файл
pathConfig = os.path.join(homeDir,".calculate","ini.env")
# Очистка файла в случае его ошибочного чтения
if isLoadVarsIni is False and os.path.exists(pathConfig):
if not self.prevDictIni and os.path.exists(pathConfig):
FD = open(pathConfig, "r+")
FD.truncate(0)
FD.seek(0)
FD.close()
# Запись переменных
# Создание объкта парсера
# Создание объекта парсера
config = cl_base.iniParser(pathConfig)
# секции будущего конфигурационного файла
sects = list(set(map(lambda x: x.split(".")[0],\
localVarsIni.keys())))
self.currDictIni.keys())))
# запись переменных в файл
for sect in sects:
dictVar = {}
for varName in localVarsIni.keys():
for varName in self.currDictIni.keys():
if varName.startswith("%s."%sect):
nameVar = varName.rpartition(".")[2]
valueVar = localVarsIni[varName]
valueVar = self.currDictIni[varName]
if valueVar:
dictVar[nameVar] = valueVar
if dictVar:
# Запись переменных в секцию
config.setVar(sect, dictVar)
# Меняем права
if os.path.exists(pathConfig) and uid and gid:
os.chown(pathConfig, int(uid), int(gid))
if os.path.exists(pathConfig):
fd = os.open(pathConfig, os.O_RDONLY)
fst = os.fstat(fd)
uid = fst.st_uid
gid = fst.st_gid
os.close(fd)
if self.uid!=uid or self.gid!=gid:
os.chown(pathConfig, int(self.uid), int(self.gid))
self.timeIni = getTimeFile(pathConfig)
return textProfileTmp
def applyTermsProfile(self, textProfile, nameProfile, nameSystemFile=False):
@ -3291,6 +3291,12 @@ class profile(_file, _terms, xmlShare, processingTemplates):
self.dictTemplates = {}
# Количество шаблонов
self.allTemplates = 0
# Время доступа к конфигурационному файлу функции шаблона ini()
self.timeIni = -1
# Первоначальный словарь переменных для ini()
self.prevDictIni = {}
# Текущий словарь переменных для ini()
self.currDictIni = {}
if self._servDir:
tmpDirsProfiles = []
for dirP in dirsProfiles:

Loading…
Cancel
Save