示例#1
0
文件: views.py 项目: Ishayahu/hasadim
def show_settings(request):
    # a=open(os.path.sep.join((os.getcwd(),'user_settings','test_file.py')),'w')
    
    # raise NotImplementedError("Надо корректно обрабатывать настройки, связанные с БД!! например, место по умолчанию, статус по умолчанию+сделать, чтобы при редактировании всё было правильно")
    # Надо корректно обрабатывать настройки, связанные с БД!! например, место по умолчанию, статус по умолчанию
    #+сделать, чтобы при редактировании всё было правильно
    
    # class Setting():
        # def __init__(self, option, value, name, description, from_bd):
            # self.name = name
            # self.value = value.replace('\n','<p>')
            # self.description = description
            # self.option = option
            # self.from_bd = from_bd
    class Settings_group():
        def __init__(self,name,description):
            self.name = name
            self.settings = []
            self.description = description
    settings=[]
    config=ConfigParser.RawConfigParser()
    config.read(config_file)
    for section in config.sections():
        setting_goup = Settings_group(section,get_section_description(section))
        for item in config.items(section):
            # Не включаем описания и названия опций
            if item[0][-12:]=='_description' or item[0][-5:]=='_name' or item[0][-5:]=='_help':
                continue
            # Настройки, связанные со значениями в БД
            if item[0][:6]=='__bd__':
                if item[0][:12]=='__bd__name__':
                    option = item[0][12:]
                    # return name,opt_id,opt_val,desc
                    # Надо, чтобы при отображении в шаблоне редактировалось оно как список!
                    # name,opt_id,opt_val,desc = get_bd_option_with_description(section,option)
                    full_option = get_full_bd_option(section,option)
                    # setting_goup.settings.append(Setting(option, opt_id+";"+opt_val, name, desc, 1))
                    setting_goup.settings.append(full_option)
            # Все остальные настройки
            else: 
                # setting_goup.settings.append(Setting(*get_option_with_name_and_description(section,item[0]), from_bd=0))
                full_option = get_full_option(section,item[0])
                setting_goup.settings.append(full_option)
        settings.append(setting_goup)
    return (True,('show_settings.html', {},{'settings':settings,},request,app))
示例#2
0
def save_by_http(request, group, key, source, status, message, TTL,
                 api_key_got):
    from user_settings.functions import get_full_option
    # getting API key
    api_key = get_full_option('save_state','api_key').value
    # print api_key.value
    # print api_key_got
    print (group, key, source, status, message, TTL,
                 api_key_got)
    if api_key != api_key_got:
        return HttpResponseForbidden('')
    next_report = datetime.datetime.now() + \
                  datetime.timedelta(minutes=int(TTL))
    status = Status(group=group, key=key,source=source,status=status,
                    message=message,
                    timestamp=datetime.datetime.now(),
                    next_report=next_report)
    status.save()
    responce = HttpResponse()
    # responce.status_code = 200
    return responce
示例#3
0
def show_user_settings(request,for_user_login):
    class Settings_group():
        def __init__(self,name,description):
            self.name = name
            self.settings = []
            self.description = description
    lang,login,user,method = get_info(request)
    if user not in admins and for_user_login:
        return (False,HttpResponseRedirect('/'))
    settings=[]
    config=ConfigParser.RawConfigParser()
    config.read(config_file)
    section = '{0}_settings'.format(login)
    try:
        setting_goup = Settings_group(section,get_section_description(section))
        for item in config.items(section):
            # Не включаем описания и названия опций
            if item[0][-12:]=='_description' or item[0][-5:]=='_name' or item[0][-5:]=='_help':
                continue
            # Настройки, связанные со значениями в БД
            if item[0][:6]=='__bd__':
                if item[0][:12]=='__bd__name__':
                    option = item[0][12:]
                    # return name,opt_id,opt_val,desc
                    # Надо, чтобы при отображении в шаблоне редактировалось оно как список!
                    # name,opt_id,opt_val,desc = get_bd_option_with_description(section,option)
                    full_option = get_full_bd_option(section,option)
                    # setting_goup.settings.append(Setting(option, opt_id+";"+opt_val, name, desc, 1))
                    setting_goup.settings.append(full_option)
            # Все остальные настройки
            else:
                # setting_goup.settings.append(Setting(*get_option_with_name_and_description(section,item[0]), from_bd=0))
                full_option = get_full_option(section,item[0])
                setting_goup.settings.append(full_option)
        settings.append(setting_goup)
    except ConfigParser.NoSectionError:
        settings=None
    return (True,('show_settings.html', {},{'settings':settings,},request,app))
示例#4
0
def show_settings(request):
    class Settings_group():
        def __init__(self,name,description):
            self.name = name
            self.settings = []
            self.description = description
    settings=[]
    config=ConfigParser.RawConfigParser()
    config.read(config_file)
    for section in config.sections():
        setting_goup = Settings_group(section,get_section_description(section))
        for item in config.items(section):
            # Не включаем описания и названия опций
            if item[0][-12:]=='_description' or item[0][-5:]=='_name' or item[0][-5:]=='_help':
                continue
            # Настройки, связанные со значениями в БД
            if item[0][:6]=='__bd__':
                if item[0][:12]=='__bd__name__':
                    option = item[0][12:]
                    # return name,opt_id,opt_val,desc
                    # Надо, чтобы при отображении в шаблоне редактировалось оно как список!
                    # name,opt_id,opt_val,desc = get_bd_option_with_description(section,option)
                    full_option = get_full_bd_option(section,option)
                    # setting_goup.settings.append(Setting(option, opt_id+";"+opt_val, name, desc, 1))
                    setting_goup.settings.append(full_option)
            # Все остальные настройки
            else: 
                # setting_goup.settings.append(Setting(*get_option_with_name_and_description(section,item[0]), from_bd=0))
                full_option = get_full_option(section,item[0])
                setting_goup.settings.append(full_option)
        settings.append(setting_goup)
        # получаем список модулей, доступных для подключения в меню
    modules = Settings_group('Модули','Доступные модули для системы')
    import os
    import os.path
    from functions import Option
    # [('assets_name', ''), ('section_description', '\xd0\x9f\xd0\xbe\xd0\xb4\xd0\xba\xd0\xbb\xd1\x8e\xd1\x87\xd1\x91\xd0\xbd\xd0\xbd\xd1\x8b\xd0\xb5 \xd0\xbc\xd0\xbe\xd0\xb4\xd1\x83\xd0\xbb\xd0\xb8'), ('assets_description', ''), ('assets', 'True')]
    # получаем списки модулей, которые находятся в настройках
    try:
        connected_modules = [x[0] for x in config.items('modules')]
    except ConfigParser.NoSectionError:
        connected_modules=[]
    # print connected_modules
    cur_dir = os.getcwd()
    for record in os.listdir('.'):
        if os.path.isdir(record):
            temp_dir = os.path.join(cur_dir,record)
            # os.chdir(temp_dir)
            if 'todoes_module' in os.listdir(temp_dir):
                lines = codecs.open(os.path.join(cur_dir,
                                          record,
                                          'todoes_module'),
                                    'r',
                                    encoding='utf-8').readlines()
                lines = [line.strip() for line in lines]
                if lines and lines[0]==u'MODULE_DESCRIPTION_v_1':
                    # проверяем, не включён ли он
                    if record in connected_modules:
                        modules.settings.append(Option(
                            section=u'Модули',
                            option=record,
                            val='True',
                            name=lines[1],
                            desc=lines[2],
                            help_message=lines[3],
                            from_bd=0,
                            opt_id=None,
                            option_type='CONNECT'
                        ))
                    else:
                        # если не подключён
                        modules.settings.append(Option(
                            section=u'Модули',
                            option=record,
                            val='False',
                            name=lines[1],
                            desc=lines[2],
                            help_message=lines[3],
                            from_bd=0,
                            opt_id=None,
                            option_type='CONNECT'
                        ))
    # для каждого модуля надо проверить, есть ли он в настройках
    # если нет - то можно его подключить и добавить в настройки,
    # если есть показываем статус из настроек. Данные для модуля
    # будем брать из файла todoes_module. Если в нём не правильные
    # данные - выдаём про него отдельное сообщение
    settings.append(modules)
    return (True,('show_settings.html',
                  {},
                  {'settings':settings,
                   # 'modules':modules,
                   },
                  request,
                  app))