class Config(): '''配置文件解析器''' def __init__(self, cfgfile): pass self.cfg = ConfigParser() self.cfg.read(cfgfile) self._parse() def _get_section(self): sections = self.cfg.sections() return sections def _get_option(self, sec): return self.cfg.options(sec) def _parse(self): sections = self.cfg.sections() programs = {} for sec in sections: if sec.startswith('program'): try: pname = sec.split(':')[1] pmodule = self.cfg.get(sec,'module') pclass= self.cfg.get(sec,'class') pmodule_path= self.cfg.get(sec,'module_path') programs[pname] = {'module': pmodule, 'class': pclass, 'module_path':pmodule_path} except Exception, e: print e pass elif sec == "general": try: pidpath= self.cfg.get(sec, 'pidpath') self.pidpath = pidpath except Exception, e: self.pidpath = "/var/tmp" print e
def setconfig(self,opts,option_value): config_default_file = "%s/%s" % (config_default_dir,self.configName) config_def = ConfigParser() config_def.read(config_default_file) config2 = ConfigParser() config2.read(self.config) secs = config_def.sections() secs_have = config2.sections() for sec in secs: kvs = config_def.items(sec) if sec not in secs_have: config2.add_section(sec) secs_have.append(sec) for value in kvs: config2.set(sec,value[0],value[1]) if opts: if "input" not in secs_have: config2.add_section("input") secs_have.append("input") for value in opts: if value[0] != "output_dir": config2.set("input",value[0],value[1]) else: config2.set("input","input_dir",value[1]) for key,value in option_value.items(): if "param" not in secs_have: config2.add_section("param") secs_have.append("param") config2.set("param",key,value) if "output" not in secs_have: config2.add_section("output") secs_have.append("output") config2.set("output","output_dir",self.path) config2.write(open(self.config,mode="w"))
class Ini(): """ Module to read ini files to a dictionary Future, develop to write to ini files """ def __init__(self, filename): self.settings = ConfigParser() self.settings.read(filename) if len(self.settings.sections()) == 0: raise IOError("Could not open ini file: %s" % (filename, )) def read(self): """ 'Read' returns a dictionary with the contents of the ini file nominated at class initiation """ output = {} sections = self.settings.sections() for section in sections: options = self.settings.options(section) output[section] = {} for option in options: output[section][option] = self.settings.get(section, option) return output def write(self): """ 'Write' function not yet implemented """ pass
def createDictFromConfig(): """ Read the configuration from scipion/config/scipionbox.conf. A dictionary will be created where each key will be a section starting by MICROSCOPE:, all variables that are in the GLOBAL section will be inherited by default. """ # Read from users' config file. confGlobalDict = OrderedDict() confDict = OrderedDict() cp = ConfigParser() cp.optionxform = str # keep case (stackoverflow.com/questions/1611799) confFile = pw.getConfigPath("scipionbox.conf") print "Reading conf file: ", confFile cp.read(confFile) GLOBAL = "GLOBAL" MICROSCOPE = "MICROSCOPE:" if not GLOBAL in cp.sections(): raise Exception("Missing section %s in %s" % (GLOBAL, confFile)) else: for opt in cp.options(GLOBAL): confGlobalDict[opt] = cp.get(GLOBAL, opt) for section in cp.sections(): if section != GLOBAL and section.startswith(MICROSCOPE): sectionDict = OrderedDict(confGlobalDict) for opt in cp.options(section): sectionDict[opt] = cp.get(section, opt) confDict[section.replace(MICROSCOPE, '')] = sectionDict return confDict
def main(args=None): ''' Main entrypoint for this application ''' # Parse command line arguments args, parser = parse_commandline_arguments(args) args.config = os.path.abspath(os.path.expanduser(args.config)) # Setup logging logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, format='%(levelname)s: %(message)s') # Create a configuration file if it does not exist if not os.path.exists(args.config): log.warn('Creating config file because it does not exist: {0}'.format(args.config)) with open(args.config, 'w') as file: file.write(DEFAULT_SECTION.format(display=os.environ.get('DISPLAY', ':0'))) # Read profile configuration config = ConfigParser() config.read(args.config) log.debug('Read xrandr profile information from: {0}'.format(args.config)) log.debug('Found {0} known profiles: {1}'.format(len(config.sections()), config.sections())) return args.func(args, config=config)
def parse_config(configs): """ :type configs list :rtype: ConfigParser """ conf = ConfigParser() all_configs = [] while len(configs) > 0: all_configs += configs files = [] for mask in configs: for f in glob.glob(mask): if os.path.isfile(f): files.append(f) conf.read(files) configs = [] if conf.has_option(DEFAULT_SECTION, "include"): configs = list(set(re.split(r'\s+', conf.get(DEFAULT_SECTION, "include"))) - set(all_configs)) for section in conf.sections(): for k, v in conf.items(DEFAULT_SECTION): if not conf.has_option(section, k): conf.set(section, k, v) for k, v in conf.items(section): v = re.sub(r'^\s*"|"\s*$', '', v) # remove quotes conf.set(section, k, v) conf.remove_section(DEFAULT_SECTION) if not conf.sections(): usage("No sections found in config files " + ", ".join(all_configs)) return conf
def init_server(): logger = logging.getLogger('EucaAggregate') fileHandler = logging.FileHandler('/var/log/euca.log') fileHandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')) logger.addHandler(fileHandler) fileHandler.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG) configParser = ConfigParser() configParser.read(['/etc/sfa/eucalyptus_aggregate.conf', 'eucalyptus_aggregate.conf']) if len(configParser.sections()) < 1: logger.error('No cloud defined in the config file') raise Exception('Cannot find cloud definition in configuration file.') # Only read the first section. cloudSec = configParser.sections()[0] AggregateManagerEucalyptus.cloud['name'] = cloudSec AggregateManagerEucalyptus.cloud['access_key'] = configParser.get(cloudSec, 'access_key') AggregateManagerEucalyptus.cloud['secret_key'] = configParser.get(cloudSec, 'secret_key') AggregateManagerEucalyptus.cloud['cloud_url'] = configParser.get(cloudSec, 'cloud_url') cloudURL = AggregateManagerEucalyptus.cloud['cloud_url'] if cloudURL.find('https://') >= 0: cloudURL = cloudURL.replace('https://', '') elif cloudURL.find('http://') >= 0: cloudURL = cloudURL.replace('http://', '') (AggregateManagerEucalyptus.cloud['ip'], parts) = cloudURL.split(':') # Create image bundles images = self.getEucaConnection().get_all_images() AggregateManagerEucalyptus.cloud['images'] = images AggregateManagerEucalyptus.cloud['imageBundles'] = {} for i in images: if i.type != 'machine' or i.kernel_id is None: continue name = os.path.dirname(i.location) detail = {'imageID' : i.id, 'kernelID' : i.kernel_id, 'ramdiskID' : i.ramdisk_id} AggregateManagerEucalyptus.cloud['imageBundles'][name] = detail # Initialize sqlite3 database and tables. dbPath = '/etc/sfa/db' dbName = 'euca_aggregate.db' if not os.path.isdir(dbPath): logger.info('%s not found. Creating directory ...' % dbPath) os.mkdir(dbPath) conn = connectionForURI('sqlite://%s/%s' % (dbPath, dbName)) sqlhub.processConnection = conn Slice.createTable(ifNotExists=True) EucaInstance.createTable(ifNotExists=True) Meta.createTable(ifNotExists=True) # Start the update process to keep track of the meta data # about Eucalyptus instance. Process(target=AggregateManagerEucalyptus.updateMeta).start() # Make sure the schema exists. if not os.path.exists(AggregateManagerEucalyptus.EUCALYPTUS_RSPEC_SCHEMA): err = 'Cannot location schema at %s' % AggregateManagerEucalyptus.EUCALYPTUS_RSPEC_SCHEMA logger.error(err) raise Exception(err)
def parse_config(): """Function to parse the config file.""" config_file = glob.glob('config.ini') parser = ConfigParser() if config_file: print 'Found a config file in working directory' parser.read(config_file) try: if 'Logging' in parser.sections(): log_dir = parser.get('Logging', 'log_file') else: log_dir = '' if 'Auth' in parser.sections(): auth_db = parser.get('Auth', 'auth_db') auth_user = parser.get('Auth', 'auth_user') auth_pass = parser.get('Auth', 'auth_pass') else: auth_db = '' auth_user = '' auth_pass = '' collection = parser.get('Database', 'collection_list') whitelist = parser.get('URLS', 'file') sources = parser.get('URLS', 'sources').split(',') pool_size = int(parser.get('Processes', 'pool_size')) return collection, whitelist, sources, pool_size, log_dir, auth_db, auth_user, auth_pass except Exception, e: print 'Problem parsing config file. {}'.format(e)
def test_crud(): report = crudminer.analyze_dir(TESTDIR, CRUDFILE, True) results = [] for (path, crudp, state, foundver) in report: results.append((crudp.name, crudp.secure, state, foundver)) crudcfg = ConfigParser() crudcfg.read(CRUDFILE) testcfg = ConfigParser() testcfg.read(TESTDIR + '/test.ini') for section in crudcfg.sections(): yield check_sections, section, testcfg.sections() if section not in testcfg.sections(): continue secure = crudcfg.get(section, 'secure') failver = testcfg.get(section, 'failver') testlist = (section, secure, 'vulnerable', failver) yield compare_results, testlist, results # pop it from the result, so matches are faster results.remove(testlist)
def main(): config = ConfigParser() config.read("config/config.cfg") # Cantidad de secciones sections = config.sections() print("%d secciones:" % len(sections)) # Imprimimos cada una de ellas for section in sections: print(section) # Leemos la cantidad de temas themes_count = config.getint("general", "temas") print(themes_count, type(themes_count)) for section in config.sections(): print("\n[%s]" % section) for item in config.items(section): print(item[0], ":", item[1]) if(item[0] == "path_origen"): print (">>>",item[1],"<<<") move_files(str(item[1]).replace('"', '')) #Elimina las comillas del path # Modificamos el tema principal config.set("general", "temas", themes_count + 1) # Agregamos un nuevo tema (sección) #config.add_section("TEMA3") config.set("videos", "nom", "listado pelis") # Removemos el ítem "votos" de la sección "TEMA2" #config.remove_option("TEMA2", "votos") # Guardamos los cambios with open("config.cfg", "w") as f: config.write(f)
class Settings(object): def __init__(self, settings_file=get_config_file()): self.config = ConfigParser() self.config.read(settings_file) def _get_section_settings(self, section): if section not in self.config.sections(): return None else: section_settings = {} options = self.config.options(section) for option in options: value = self.config.get(section, option) if value[0] == '(' and value.__len__() > 1: value = value.replace("(", "").\ replace(")", "").\ replace("\'", "") value = tuple(value.split(", ")) if value == "None": value = None section_settings[option] = value return section_settings def __getattr__(self, name): if name in self.config.sections(): return self._get_section_settings(name) else: return self.config.sections()
def getInstance(cls, application, connection, *args, **kwargs): parser = ConfigParser() parser.read(cls.getApplicationConfig(application, 'connections.conf')) # if alias, resolve alias if connection not in parser.sections(): for section in parser.sections(): try: if connection in (i.strip() for i in parser.get(section, 'aliases').split(',')): connection = section break except NoOptionError: pass provider = parser.get(connection, 'provider') driver = lang.import_module_relative(provider, __name__, 'driver').DbiDriver data = { 'host' : parser.get(connection, 'host' ), 'database' : parser.get(connection, 'dbname' ), 'user' : parser.get(connection, 'username'), 'password' : parser.get(connection, 'password'), '_encoding_' : parser.get(connection, 'encoding'), } try: data['port'] = parser.get(connection, 'port') except: pass return driver(application, data, *args, **kwargs)
class IniDict(UserDict,object): _getformater=None _setformater=None def __init__(self,fp='',encoding='utf-8'): UserDict.__init__(self) self.cp=ConfigParser() self.path=fp self.encoding=encoding if fp:self.load(self.path) def load(self,p=''): if not p:p=self.path self.cp.read(p) self.update(dict(map(lambda i:(i,dict(self.cp.items(i))),self.cp.sections()))) if self._getformater: for i in self.keys(): for j in self[i]: self[i][j]=self._getformater(self[i][j]) def save(self,p=''): if not p:p=self.path for i in self.keys(): if i not in self.cp.sections(): i.add_section(i) for j in self[i].keys(): if self._setformater:self.cp.set(i,j,self._setformater(self[i][j])) else:cp.set(i,j,self[i][j]) self.cp.write(open(p,"w")) def addGetFormater(self,func): if self._getformater:self._getformater=lambda s:func(self._getformater(s)) else:self._getformater=func self.load() def addSetFormater(self,func): if self._setformater:self._setformater=lambda s:self._setformater(func(s)) else:self._setformater=func self.save()
def read_config(): config = ConfigParser() if not config.read(config_file): raise AutoConnException('ConfigFileError', 'Configuration file missing.') elif 'ddns' not in config.sections(): raise AutoConnException('ConfigFileError', 'Missing section `ddns`.') elif 'connect' not in config.sections(): raise AutoConnException('ConfigFileError', 'Missing section `connect`.') return config
def load_config(config_file): parser = ConfigParser() parser.read(config_file) parser.sections() for section in parser.sections(): add_host(section, parser.get(section, 'ip')) # os.system('./add_host.sh {} {}'.format(section, parser.get(section, 'ip'))) parser.remove_option(section, 'ip') for service, command in parser.items(section): add_service_to_host(section, service, command)
class Config(object): """ handle to captive portal config (/usr/local/etc/captiveportal.conf) """ _cnf_filename = "/usr/local/etc/captiveportal.conf" def __init__(self): """ consctruct new config object """ self.last_updated = 0 self._conf_handle = None self._update() def _update(self): """ check if config is changed and (re)load """ mod_time = os.stat(self._cnf_filename)[stat.ST_MTIME] if os.path.exists(self._cnf_filename) and self.last_updated != mod_time: self._conf_handle = ConfigParser() self._conf_handle.read(self._cnf_filename) self.last_updated = mod_time def get_zones(self): """ return list of configured zones :return: dictionary index by zoneid, containing dictionaries with zone properties """ result = dict() self._update() if self._conf_handle is not None: for section in self._conf_handle.sections(): if section.find('zone_') == 0: zoneid = section.split('_')[1] result[zoneid] = dict() for item in self._conf_handle.items(section): result[zoneid][item[0]] = item[1] # convert allowed(MAC)addresses string to list if 'allowedaddresses' in result[zoneid] and result[zoneid]['allowedaddresses'].strip() != '': result[zoneid]['allowedaddresses'] = \ map(lambda x: x.strip(), result[zoneid]['allowedaddresses'].split(',')) else: result[zoneid]['allowedaddresses'] = list() if 'allowedmacaddresses' in result[zoneid] and result[zoneid]['allowedmacaddresses'].strip() != '': result[zoneid]['allowedmacaddresses'] = \ map(lambda x: x.strip(), result[zoneid]['allowedmacaddresses'].split(',')) else: result[zoneid]['allowedmacaddresses'] = list() return result def fetch_template_data(self, zoneid): """ fetch template content from config """ for section in self._conf_handle.sections(): if section.find('template_for_zone_') == 0 and section.split('_')[-1] == str(zoneid): if self._conf_handle.has_option(section, 'content'): return self._conf_handle.get(section, 'content') return None
def init_from_options(self): # If a config file is provided, read it into the ABACManager if self._options.config: cp = ConfigParser() cp.optionxform=str cp.read(self._options.config) for name in cp.options('Principals'): cert_file = cp.get('Principals', name) self.register_id(name, cert_file) for name in cp.options('Keys'): key_file = cp.get('Keys', name) self.register_key(name, key_file) if 'Assertions' in cp.sections(): for assertion in cp.options('Assertions'): self.register_assertion(assertion) if 'AssertionFiles' in cp.sections(): for assertion_file in cp.options("AssertionFiles"): self.register_assertion_file(assertion_file) # Use all the other command-line options to override/augment # the values in the ABCManager # Add new principal ID's / keys if self._options.id: for id_filename in options.id: parts = id_filename.split(':') id_name = parts[0].strip() id_cert_file = None if len(parts) > 1: id_cert_file = parts[1].strip() self.register_id(id_name, id_cert_file) id_key_file = None if len(parts) > 2: id_key_file = parts[2].strip() self.register_key(name, id_key_file) # Register assertion files provided by command line if self._options.assertion_file: for assertion_file in self._options.assertion_file: self.register_assertion_file(assertion_file) # Grab pure ABAC assertions from commandline if self._options.assertion: for assertion in self._options.assertion: self.register_assertion(assertion)
def __Logger_cache_options(self): """ **(private)** Read and cache debug levels for categories from config file. """ configfilename = self.__Logger_find_config() if (configfilename != ""): parser = ConfigParser() parser.read(configfilename) for i in range(len(parser.sections())): section = parser.sections()[i] if (section != SECTION_DEFAULT): instance = self.get_instance(section) self.__Logger_set_instance_options(parser, section, instance) return TRUE
def assertProfilesEqual(profile_filename_a, profile_filename_b, skip_sections=None, skip_options=None): """ Compares two profiles """ if skip_options is None: skip_options = {'local_ip_address', 'description', 'name'} if skip_sections is None: skip_sections = {'target'} original = ConfigParser() original.read(profile_filename_a) saved = ConfigParser() saved.read(profile_filename_b) # # Analyze in one way # for section_name in original.sections(): for orig_name, orig_value in original.items(section_name): if orig_name in skip_options: continue if section_name in skip_sections: continue saved_value = saved.get(section_name, orig_name) msg = ('The "%s" option of the "%s" section changed from' ' "%s" to "%s"') args = (orig_name, section_name, orig_value, saved_value) assert saved_value == orig_value, msg % args # # And then the other # for section_name in saved.sections(): for saved_name, saved_value in saved.items(section_name): if saved_name in skip_options: continue if section_name in skip_sections: continue orig_value = original.get(section_name, saved_name) msg = ('The "%s" option of the "%s" section changed from' ' "%s" to "%s"') args = (saved_name, section_name, orig_value, saved_value) assert saved_value == orig_value, msg % args
def readConstraintsFile(staff_file): """Retrieve staff constraints from staff config file.""" parser = ConfigParser() parser.readfp(staff_file) staffList = [] for staffName in parser.sections(): if staffName == "General": continue if parser.has_option(staffName, "canworkweekdays"): strList = parser.get(staffName, "canworkweekdays").split() canWorkWeekdays = [int(s) for s in strList] else: canWorkWeekdays = range(7) if parser.has_option(staffName, "fixedShifts"): fixed = parser.getboolean(staffName, "fixedShifts") else: fixed = False cantWorkDates = [] if parser.has_option(staffName, "cantworkdates"): strList = parser.get(staffName, "cantworkdates").split(',') for dateRangeStr in strList: dateRange = dateRangeStr.split('to') if len(dateRange) == 1: thisdate = datetime.strptime(dateRange[0].strip(), "%d/%m/%y") cantWorkDates.append(thisdate) else: startDate = datetime.strptime(dateRange[0].strip(), "%d/%m/%y") endDate = datetime.strptime(dateRange[1].strip(), "%d/%m/%y") nDays = (endDate-startDate).days+1 dates = [startDate + timedelta(i) for i in range(nDays)] cantWorkDates.extend(dates) staffList.append(Employee(staffName, canWorkWeekdays=canWorkWeekdays, cantWorkDates=cantWorkDates, fixed=fixed)) if ("General" not in parser.sections()) or not parser.has_option("General", "shiftsPerDay"): print "Error: Shifts per day not specified in constraints file." exit(1) shiftsPerDay = [int(s) for s in parser.get("General", "shiftsPerDay").split()] return staffList, shiftsPerDay
def values(self): # get schemas defaults schema = self._schema_ values = self._default_values_() # let's parse configuration file cp = ConfigParser() cp.read(self._configuration_file_) # Sections verifications unused_sections = [section for section in cp.sections() \ if section not in schema.keys()] if unused_sections != []: raise ConfigurationSectionNotUsed, \ "Section(s) not used in configuration file : %s" % \ ' '.join(unused_sections) not_found_sections = [section for section in schema.keys() \ if section not in cp.sections()] if not_found_sections != []: raise ConfigurationSectionNotFound, \ "Section(s) not found in configuration file : %s" % \ ' '.join(not_found_sections) # Options verifications and merging for section in schema: not_used_options = [option for option in cp.options(section) \ if option not in schema[section] and not '_any_' in schema[section]] if not_used_options != []: raise ConfigurationOptionNotUsed, \ 'Option(s) not used in section \'%s\' : %s' % \ (section, ' '.join(not_used_options)) for option in cp.options(section): if option in schema[section]: t = schema[section][option]['type'] elif 'any' in schema[section]: t = schema[section]['_any_']['type'] try: v = t( cp.get(section,option) ) except ValueError: raise ConfigurationOptionTypeMismatch, \ 'Option \'%s\' must be \'%s\'' % (option, t.__name__) if section == 'default': values[option] = v else: values['%s.%s' % (section, option)] = v return values
class CReader(object): ''' Simple config file reader ''' def __init__(self,fn): ''' Constructor ''' self.fn = fn self.cp = ConfigParser() self.cp.read(fn) def listSections(self): return self.cp.sections() def hasSection(self,secname): return secname in self.getSections() def getSections(self): return self.cp.sections() def _readSec(self,sec,opts): ovdic = {} for o in opts: try: val = self.cp.get(sec,str(o)) except NoSectionError: print 'No Sec',sec raise except NoOptionError as noe: print 'No Opt',str(o) raise ovdic[str(o)] = val return ovdic def readHDSection(self,secname): return self._readSec(secname,('header','data')) def readUPSection(self,secname): return self._readSec(secname,('user','pass')) def readArcGISSection(self,secname): return self._readSec(secname,('uname','sname','ctype','desc','cats','url','opts','scan')) def readSecOpt(self,sec,opt): return self.cp.get(sec, opt)
class BaseDropbox(object): def __init__(self): APP_KEY = 'oqnyxvnwr67ebpc' APP_SECRET = 'd5qiseh1lnfzayh' CONFIG_PATH = '~/.dbxrc' self.parser = ConfigParser() self.path = path.expanduser(CONFIG_PATH) if path.exists(self.path): self.parser.read(self.path) if 'auth' not in self.parser.sections(): self.parser.add_section('auth') if 'general' not in self.parser.sections(): self.parser.add_section('general') self.parser.set('general', 'home', 'Dropbox') if self.parser.has_option('auth', 'token'): access_token = self.parser.get('auth', 'token') else: auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET) authorize_url = auth_flow.start() print "1. Go to: " + authorize_url print "2. Click \"Allow\" (you might have to log in first)." print "3. Copy the authorization code." auth_code = raw_input("Enter the authorization code here: ").strip() try: access_token, user_id = auth_flow.finish(auth_code) print 'Authenticated user: %s' % user_id except rest.ErrorResponse, e: print('Error: %s' % (e,)) return self.parser.set('auth', 'token', access_token) with open(self.path, 'w') as writer: self.parser.write(writer) self.client = DropboxClient(access_token) self.manager = DatastoreManager(self.client) self.datastore = self.manager.open_default_datastore() self.commit_table = self.datastore.get_table('commit_table')
class SecretSanta(object): def __init__(self, config): log.debug("Constructing SecretSanta main object.") self.people = [] self.givers = [] self.receivers = [] self.pcfile = config.get('global','peopleconf') log.debug("Peopleconf is %s" % self.pcfile) self.pc=ConfigParser() self.pc.read(self.pcfile) for sect in self.pc.sections(): p = SecretSantaPerson(sect, self.pc) self.people.append(p) for p in self.givers: self.receivers.append(p) def matchall(self): ''' Perform matching for all people with constraints. ''' rlist = [] for p in self.people: rlist.append(p) shuffle(rlist) log.debug("Performing matching...") for p in self.people: r = rlist.pop() while not p.matchok(r): rlist.append(r) shuffle(rlist) r = rlist.pop() p.receiver = r log.debug("%s -> %s\n" % (p.name, p.receiver.name)) def list(self): ''' Return string representation of all people in config. ''' log.debug("List all users...") s = "" for p in self.people: s+= str(p) return s def giverslist(self): ''' Return string in form of: Joe Bloe -> Mary Margaret Mary Margaret -> Susan Strong Susan Strong -> Joe Bloe ''' s = "" for p in self.people: s+= "%s -> %s\n" % ( p.name, p.receiver.name) return s
def read_config(self, config_path): config_parser = ConfigParser() config_parser.read(config_path) for section in config_parser.sections(): for option in config_parser.options(section): value = config_parser.get(section, option) setattr(self, option, value)
def _set_config_all(self, path_to_file): out = sys.stdout if not os.access(path_to_file, os.R_OK): self.log.warning( "cannot access file %s" % path_to_file ) return elif not self.env.config: self.log.warning( "cannot access config file trac.ini" ) return cfg = ConfigParser() cfg.read(path_to_file) if os.access(self.env.path, os.W_OK): path_to_trac_ini = os.path.join(self.env.path, 'conf', 'trac.ini') shutil.copy(path_to_trac_ini, path_to_trac_ini + '.bak') out.write( "created a backup of trac.ini to %s.bak" % path_to_trac_ini ) out.write('\n') else: out.write( "could not create backup of trac.ini - continue anyway? [y|n] " ) input = sys.stdin.readline() if not input or not input.strip() == 'y': return for sect in cfg.sections(): for opt in cfg.options(sect): self.config.set(sect, opt, cfg.get(sect, opt)) out.write( "added config [%s] %s = %s" % (sect, opt, cfg.get(sect, opt)) ) out.write('\n') self.config.save()
def startService(self): BaseUpstreamScheduler.startService(self) log.msg("starting l10n scheduler") if self.inipath is None: # testing, don't trigger tree builds return # trigger tree builds for our trees, clear() first cp = ConfigParser() cp.read(self.inipath) self.trees.clear() _ds = [] for tree in cp.sections(): # create a BuildSet, submit it to the BuildMaster props = properties.Properties() props.update({ 'tree': tree, 'l10nbuilds': self.inipath, }, "Scheduler") bs = buildset.BuildSet([self.treebuilder], SourceStamp(), properties=props) self.submitBuildSet(bs) _ds.append(bs.waitUntilFinished()) d = defer.DeferredList(_ds) d.addCallback(self.onTreesBuilt) self.waitOnTree = d
def process_config(directory, config_file, sp): config = ConfigParser() config.read(config_file) sections = config.sections() db_or_element = db_or_element_format(sp, sections) if db_or_element == "db": invalid_sections = fc.invalid_config_sections(directory, config_file, sp.full_header_data("db")) elif db_or_element == "element": invalid_sections = fc.invalid_config_sections(directory, config_file, sp.full_header_data("element")) else: return "error" for s in sections: fname = config.get(s, "file_name") header = config.get(s, "header") if s in invalid_sections: if os.path.exists(directory + fname): os.remove(directory + fname) else: with open(directory + s + "_temp.txt", "w") as w: w.write(header + "\n") with open(directory + fname, "r") as r: for line in r: w.write(line) os.remove(directory + fname) os.rename(directory + s + "_temp.txt", directory + fname) os.remove(config_file) if len(invalid_sections) == 0: return None return {"invalid_sections":invalid_sections}
def get_mapping_fields(self, cr, uid, shop_id, context=None, reverse=False): result = {} if not context: context = {} shop_pool = self.pool.get('sale.shop') shop_data = shop_pool.read(cr, uid, shop_id, ['prestashop_config_path']) if not shop_data['prestashop_config_path'] or \ not shop_data['prestashop_config_path'].endswith(".conf") or\ not self._prestashop: return result,False config = ConfigParser() config.read(shop_data['prestashop_config_path']) if not self._name in config.sections(): return result,False mapping = dict(config.items(self._name)) return eval(mapping.get('type_mapping',"[]"))
def getDataSources(fName = None): ''' return data sources directories for this machine. directories are defined in datasources.ini or provided filepath''' import socket from ConfigParser import ConfigParser pcName = socket.gethostname() p = ConfigParser() p.optionxform = str if fName is None: fName = 'datasources.ini' p.read(fName) if pcName not in p.sections(): raise NameError('Host name section %s not found in file %s' %(pcName,fName)) dataSources = {} for option in p.options(pcName): dataSources[option] = p.get(pcName,option) return dataSources
def parse_config_files(self, filenames=None): from ConfigParser import ConfigParser if filenames is None: filenames = self.find_config_files() if DEBUG: print "Distribution.parse_config_files():" parser = ConfigParser() for filename in filenames: if DEBUG: print " reading", filename parser.read(filename) for section in parser.sections(): options = parser.options(section) opt_dict = self.get_option_dict(section) for opt in options: if opt != '__name__': val = parser.get(section, opt) opt = string.replace(opt, '-', '_') opt_dict[opt] = (filename, val) # Make the ConfigParser forget everything (so we retain # the original filenames that options come from) parser.__init__() # If there was a "global" section in the config file, use it # to set Distribution options. if self.command_options.has_key('global'): for (opt, (src, val)) in self.command_options['global'].items(): alias = self.negative_opt.get(opt) try: if alias: setattr(self, alias, not strtobool(val)) elif opt in ('verbose', 'dry_run'): # ugh! setattr(self, opt, strtobool(val)) else: setattr(self, opt, val) except ValueError, msg: raise DistutilsOptionError, msg
def ini_config(self, conf_fn): conf_section = 'main' if '#' in conf_fn: conf_fn, conf_section = conf_fn.split('#', 1) try: from ConfigParser import ConfigParser except ImportError: from configparser import ConfigParser p = ConfigParser() # Case-sensitive: p.optionxform = str if not os.path.exists(conf_fn): # Stupid RawConfigParser doesn't give an error for # non-existant files: raise OSError("Config file %s does not exist" % self.options.config_file) p.read([conf_fn]) p._defaults.setdefault('here', os.path.dirname(os.path.abspath(conf_fn))) possible_sections = [] for section in p.sections(): name = section.strip().lower() if (conf_section == name or (conf_section == name.split(':')[-1] and name.split(':')[0] in ('app', 'application'))): possible_sections.append(section) if not possible_sections: raise OSError( "Config file %s does not have a section [%s] or [*:%s]" % (conf_fn, conf_section, conf_section)) if len(possible_sections) > 1: raise OSError( "Config file %s has multiple sections matching %s: %s" % (conf_fn, conf_section, ', '.join(possible_sections))) config = {} for op in p.options(possible_sections[0]): config[op] = p.get(possible_sections[0], op) return config
def readconf(rc,dic=None): config = ConfigParser() config.optionxform=str try: config.read( rc ) except BaseException as e: raise ValueError("Config Parser returns an error\'{}\'".format(e)) if dic is None: dic={} elif not type(dic) is dict: raise TypeError("Incorrect dictionary type") for section in config.sections(): if not section in dic: dic[section]={} elif not type(dic[section]) is dict: raise TypeError("Section {} in dictionary is not a dictionary") for option in config.options(section): dic[section][option] = config.get(section,option) return dic
def main(args=sys.argv[1:]): if len(sys.argv) != 2: exec_file = os.path.basename(sys.argv[0]) print >> sys.stderr, 'Usage: %s <config file>' % exec_file return 1 config = ConfigParser() config.read(args[0]) for section in config.sections(): if not (section.startswith('Transport ') or section.startswith('Account ')): continue name = config.get(section, 'name') try: pwd = decrypt(config.get(section, 'pass').decode('utf-8')) except NoOptionError: pwd = str() print '%s:%s' % (name, pwd) return 0
def load(self): content = memcache.get("atozproperties") if content is not None: #logging.info("Got atozproperties from memcache") return content else: #logging.info("NOT Got atozproperties from memcache") atozCopyProperties = "properties/atoz.properties" atozCfg = ConfigParser() atozCfg.read(atozCopyProperties) content = list() sections = sorted(atozCfg.sections()) for i in sections: section = {} section["section"] = i for j in atozCfg.items(i): section[j[0]] = j[1] content.append(section) memcache.add("atozproperties", content) return content
class Config_opt(object): def __init__(self, file): self.file = file self.con_option = ConfigParser() self.con_option.read(self.file) def get_sections(self): return self.con_option.sections() def get_options(self, section): return self.con_option.options(section) def get_items(self, section): return dict(self.con_option.items(section)) def get_str(self, section, option): return self.con_option.get(section, option) def get_int(self, section, option): return self.con_option.get(section, option)
def test_as_ini_other_properties(self): from DateTime.DateTime import DateTime INTPROP = 42 FLOATPROP = 3.1415926 DATESTR = '2005-11-07T12:00:00.000Z' context = _makePropertied('string_property') context._properties = () context._setProperty('int_prop', INTPROP, 'int') context._setProperty('float_prop', FLOATPROP, 'float') context._setProperty('date_prop', DateTime(DATESTR), 'date') adapter = self._getTargetClass()(context) text = adapter.as_ini() parser = ConfigParser() parser.readfp(StringIO(text)) self.failIf(parser.sections()) default_options = parser.defaults() self.assertEqual(len(default_options), 3) self.assertEqual(default_options['int_prop'], str(INTPROP)) self.assertEqual(default_options['float_prop'], str(FLOATPROP)) self.assertEqual(default_options['date_prop'], str(DateTime(DATESTR)))
def _parse_config_file(self, config_file=None): """ Helper function to parse a config file. This will overwrite any existing variables if necessary. """ log = logging.getLogger(__name__) if os.path.isfile(config_file): config = ConfigParser() config.read(config_file) log.debug('Config sections: %s', config.sections()) public_key = config.get('Default', 'public_api_key') if public_key is not None: self.public_api_key = public_key private_key = config.get('Default', 'private_api_key') if private_key is not None: self.private_api_key = private_key else: log.warn('No client config file found at %s.' % (config_file))
def extract_ini_context(request): """Extract and return context from a text/ini (ConfigParser) request.""" from ConfigParser import ConfigParser, ParsingError from cStringIO import StringIO context = {} parser = ConfigParser() if not request.body: # Quick handling of empty requests. return context try: parser.readfp(StringIO('[__globals__]\n' + request.body)) except ParsingError: raise exceptions.DataParsingError('Failed to parse INI data.') for option, value in parser.items('__globals__'): context[option] = value parser.remove_section('__globals__') for section in parser.sections(): context[section] = {} for option, value in parser.items(section): context[section][option] = value return context
def read_config(cfg): """ read config fron ini :param cfg: :return: """ check_paths(cfg) r = {} config = ConfigParser() config.read(cfg) for section in config.sections(): r[section] = {} for option in config.options(section): value = config.get(section, option).strip().decode("utf-8") r[section][option] = value return r
def _load_config(self): config_file_path = os.path.join(get_virtual_home(), '.jip') if not os.path.exists(config_file_path): config_file_path = os.path.expanduser('~/.jip') if os.path.exists(config_file_path): config = ConfigParser() config.read(config_file_path) repos = [] ## only loop section starts with "repos:" repos_sections = filter(lambda x: x.startswith("repos:"), config.sections()) for section in repos_sections: name = section.split(':')[1] uri = config.get(section, "uri") rtype = config.get(section, "type") repos.append((name, uri, rtype)) return repos else: return None
def cfgread(config_file): """ ConfigFile reader, register sections to global `CONF` instance. """ cfg = ConfigParser() if not hasattr(cfg, 'read_file'): cfg.read_file = cfg.readfp try: cfp = open(config_file) cfg.read_file(cfp) cfp.close() except: raise ConfigError("cannot open/read configfile, {0}".format(excinst())) for _cs in cfg.sections(): CONF.regisiter_opts(_cs, dict(zip( [ c[0] for c in cfg.items(_cs) ], [ c[1].strip('\'').strip('"') for c in cfg.items(_cs) ]))) return CONF
def getMachines(self): c = Cfg() c.read(self.__configLTSPFile) ret = [] for section in c.sections(): if section <> 'server': try: local = c.get(section, 'localapps') if local.upper().startswith('Y') or \ local.upper().startswith('S') or \ local.upper().startswith('T'): local = True else: local = False except: local = False try: ret.append( [section, c.get(section, 'ip'), local] ) except: pass del c return ret
def removeRepo(self, repo_id): """ Remove a given repository """ repos = self._get_repos('KCHREPOS0027E') if repo_id not in repos.keys(): raise NotFoundError("KCHREPOS0012E", {'repo_id': repo_id}) entry = repos.get(repo_id) parser = ConfigParser() with open(entry.repofile) as fd: parser.readfp(fd) if len(parser.sections()) == 1: os.remove(entry.repofile) return parser.remove_section(repo_id) with open(entry.repofile, "w") as fd: parser.write(fd)
def parse_user_config(filename, dependencies): ''' Read user_config and update the relevant fields ''' cparse = ConfigParser() cparse.read(filename) for dep_name in cparse.sections(): if not dep_name in dependencies.keys(): print('!! user_config specifies unknown dependency "{0}"'.format( dep_name)) Exit(0) # loop over options for that dependencies for opt in cparse.options(dep_name): if opt in VALID_FIELDS: dependencies[dep_name].__setattr__(opt, cparse.get(dep_name, opt)) else: print "Unknown build option: {0} for dependency {1}".format( opt, dep_name)
def __init__(self, sink, name, path): global desktop_cache DockManagerItem.__init__(self, sink, path) if name in desktop_cache: cfg = desktop_cache[name] else: cfg = ConfigParser() cfg.read(name) desktop_cache[name] = cfg try: icon = cfg.get('Desktop Entry', 'Icon') except: icon = os.path.split(name)[1].split('.')[0] self.items = {} lc = locale.getdefaultlocale()[0] names = [ 'Name[%s]' % lc, 'Name[%s]' % lc.split('_')[0], 'Name', ] for section in cfg.sections(): if section.endswith('Shortcut Group'): name = None for n in names: try: name = cfg.get(section, n) break except: pass self.add_menu_item( name, icon, 'Quicklist', ) self.items[name] = cfg.get(section, 'Exec')
def _read_pypirc(self): """Reads the .pypirc file.""" rc = self._get_rc_file() if os.path.exists(rc): self.announce('Using PyPI login from %s' % rc) repository = self.repository or self.DEFAULT_REPOSITORY config = ConfigParser() config.read(rc) sections = config.sections() if 'distutils' in sections: index_servers = config.get('distutils', 'index-servers') _servers = [ server.strip() for server in index_servers.split('\n') if server.strip() != '' ] if _servers == []: if 'pypi' in sections: _servers = ['pypi'] else: return {} for server in _servers: current = {'server': server} current['username'] = config.get(server, 'username') for key, default in (('repository', self.DEFAULT_REPOSITORY), ('realm', self.DEFAULT_REALM), ('password', None)): if config.has_option(server, key): current[key] = config.get(server, key) else: current[key] = default if current['server'] == repository or current['repository'] == repository: return current elif 'server-login' in sections: server = 'server-login' if config.has_option(server, 'repository'): repository = config.get(server, 'repository') else: repository = self.DEFAULT_REPOSITORY return {'username': config.get(server, 'username'), 'password': config.get(server, 'password'), 'repository': repository, 'server': server, 'realm': self.DEFAULT_REALM} return {}
def load_sessions(file): cp = ConfigParser(dict_type=SortedDict) cp.readfp(file) sections = cp.sections() if not sections: print >> sys.stderr, "No tab info found, aborting" sys.exit(1) # Clear existing sessions, but only if we have good info (above) clear_sessions() for section in sections: get_yakuake('/yakuake/sessions addSession') import time time.sleep(5) # Map the new sessions to their konsole session objects sessions = sorted( int(i) for i in get_yakuake('/yakuake/sessions sessionIdList').split(',')) ksessions = sorted( int(line.split('/')[-1]) for line in get_yakuake('').split('\n') if '/Sessions/' in line) session_map = SortedDict(zip(sessions, ksessions)) active = 0 # Repopulate the tabs for i, section in enumerate(sections): sessid = int(get_yakuake('/yakuake/tabs sessionAtTab %d' % i)) ksessid = '/Session/%d' % session_map[sessid] opts = dict(cp.items(section)) get_yakuake('/yakuake/sessions raiseSession %d' % sessid) get_yakuake('/yakuake/tabs setTabTitle %d "%s"' % (sessid, opts['title'])) if opts['cwd']: get_yakuake('/yakuake/sessions runCommand "cd %s"' % opts['cwd']) if opts['cmd']: get_yakuake('/yakuake/sessions runCommand "%s"' % opts['cmd']) if opts['active'].lower() in ['y', 'yes', 'true', '1']: active = sessid if active: get_yakuake('/yakuake/sessions raiseSession %d' % active)
def main(): ''' main function ''' # pylint: disable=line-too-long if ARGS.cht_api_key: api_key = ARGS.cht_api_key elif os.environ.get('CLOUDHEALTH_API_KEY', None): api_key = os.environ.get('CLOUDHEALTH_API_KEY', None) else: LOG.error( 'CloudHealth API Key missing. Use -k or set CLOUDHEALTH_API_KEY in your environment.' ) sys.exit(1) if ARGS.profile: if not os.environ.get('AWS_PROFILE', None): LOG.warn( 'AWS_PROFILE environment variable not set. Trying profile value.' ) os.environ['AWS_PROFILE'] = ARGS.profile account_number = get_account_number() LOG.info('using AWS Account: %s', account_number) external_id = setup_cloudhealth_account(api_key, account_number) setup_role_policy(account_number, name=ARGS.aws_role_name, external_id=external_id) else: LOG.warn( 'No profile specified. Looping through all profiles in credentials file.' ) awscreds = ConfigParser() awscreds.read(ARGS.credsfile) for sect in awscreds.sections(): LOG.warn('refreshing profile: %s', sect) os.environ['AWS_PROFILE'] = sect account_number = get_account_number() LOG.info('using AWS Account: %s', account_number) external_id = setup_cloudhealth_account(api_key, account_number) setup_role_policy(account_number, name=ARGS.aws_role_name, external_id=external_id)
def envs_conf(env_): defaults = { 'dbname': 'mootiro_maps', 'virtualenv': 'mootiro_maps', 'server_port': '8001', 'apache_conf': 'maps', 'maintenance_apache_conf': 'maps_maintenance' } required = ['hosts', 'dir', 'django_settings'] # Lets parse the config file to get the env attributes. conf = ConfigParser(defaults) conf.read(os.path.join(env.fabfile_dir, 'envs.conf')) available_envs = conf.sections() # Defining some messages to be displayed to user. usage_msg = 'Usage: fab use:<env> <command>' available_msg = ( 'The available envs are: "{envs}". ' 'To modify your environments edit the configuration file "envs.conf".' ).format(envs=', '.join(available_envs)) # The user should specify an env to use. if not env_: abort(''.join([ 'You should specify which "env" you want to use.\n', available_msg, '\n\n', usage_msg ])) # The env should be specified in the config file. if env_ not in available_envs: abort(''.join(['Environment not found: "{}".\n', available_msg]).format(env_)) # Verify if all required options were defined. not_defined = [i for i in required if i not in conf.options(env_)] if not_defined: abort('There are some required options not defined for "{}": {}.\n' 'Please, edit "envs.conf" file and fill all required options.\n'. format(env_, ', '.join(not_defined))) return conf
def readROIFile(hfile): cp = ConfigParser() cp.read(hfile) output = [] for a in cp.options('rois'): if a.lower().startswith('roi'): iroi = int(a[3:]) name, dat = cp.get('rois', a).split('|') lims = [int(i) for i in dat.split()] ndet = len(lims) / 2 dat = [] for i in range(ndet): dat.append((lims[i * 2], lims[i * 2 + 1])) output.append((iroi, name.strip(), dat)) roidata = sorted(output) calib = {} caldat = cp.options('calibration') for attr in ('offset', 'slope', 'quad'): calib[attr] = [float(x) for x in cp.get('calibration', attr).split()] extra = {} ndet = len(calib['offset']) file_sections = cp.sections() for section in ('dxp', 'extra'): if section not in file_sections: continue for attr in cp.options(section): tmpdat = [x for x in cp.get(section, attr).split()] if len(tmpdat) == 2 * ndet: tmpdat = [ '%s %s' % (i, j) for i, j in zip(tmpdat[::2], tmpdat[1::2]) ] try: extra[attr] = [int(x) for x in tmpdat] except ValueError: try: extra[attr] = [float(x) for x in tmpdat] except ValueError: extra[attr] = tmpdat return roidata, calib, extra
def read_config(self): from ConfigParser import ConfigParser def _eval(val): try: return eval(val) except: return str(val) filename = self._find_a_config_file() log.info("Reading Ninjo config file: '%s'" % filename) cfg = ConfigParser() cfg.read(filename) products = {} for sec in cfg.sections(): prd = {} for key, val in cfg.items(sec): prd[key] = _eval(val) products[sec] = prd self._products = products
def check_remote_profiles( self, remote_profiles_ini='/data/b2g/mozilla/profiles.ini'): if not self.dm.fileExists(remote_profiles_ini): raise Exception("Remote file '%s' not found" % remote_profiles_ini) local_profiles_ini = tempfile.NamedTemporaryFile() self.dm.getFile(remote_profiles_ini, local_profiles_ini.name) cfg = ConfigParser() cfg.readfp(local_profiles_ini) remote_profiles = [] for section in cfg.sections(): if cfg.has_option(section, 'Path'): if cfg.has_option(section, 'IsRelative') and cfg.get( section, 'IsRelative'): remote_profiles.append( posixpath.join(posixpath.dirname(remote_profiles_ini), cfg.get(section, 'Path'))) else: remote_profiles.append(cfg.get(section, 'Path')) return remote_profiles
def loadSubs(self, filename): """Load a substitutions file. The file must be in the Windows-style INI format (see the standard ConfigParser module docs for information on this format). Each section of the file is loaded into its own substituter. """ parser = ConfigParser() with open(filename) as inFile: parser.readfp(inFile, filename) for s in parser.sections(): # Add a new WordSub instance for this section. If one already # exists, delete it. if s in self._subbers: del (self._subbers[s]) self._subbers[s] = WordSub() # iterate over the key,value pairs and add them to the subber for k, v in parser.items(s): self._subbers[s][k] = v
def read_shares(self): """get invalid user from samba share conf""" if not os.path.isdir(ShareConfiguration.SHARES_UDM_DIR): return for file in os.listdir(ShareConfiguration.SHARES_UDM_DIR): filename = os.path.join(ShareConfiguration.SHARES_UDM_DIR, file) cfg = ConfigParser() cfg.read(filename) try: share = Share(cfg.sections()[0]) except IndexError: continue if cfg.has_option(share.name, Restrictions.INVALID_USERS): share.invalid_users = shlex.split(cfg.get(share.name, Restrictions.INVALID_USERS)) if cfg.has_option(share.name, Restrictions.HOSTS_DENY): share.hosts_deny = shlex.split(cfg.get(share.name, Restrictions.HOSTS_DENY)) self._shares[share.name] = share
def get_config(config_file=None): """ Retrieve app configuration parameters such as database connections :return: configuration """ global config if not config_file: if config: return config config_file = os.path.join(base_dir, 'conf/gaia.cfg') parser = ConfigParser() parser.read(config_file) config_dict = {} for section in parser.sections(): config_dict[section] = {} for key, val in parser.items(section): config_dict[section][key] = val.strip('"').strip("'") config = config_dict return config_dict
def read_from_file(filename, section, required_props=None): config_parser = ConfigParser() config_parser.optionxform = str data = dict() try: data_set = config_parser.read(filename) if len(data_set) == 0: return None if section not in config_parser.sections(): return dict() for k, v in config_parser.items(section): data[k] = v return data except IOError, e: print("read_from_file Open '%s' file failed: %s" % (filename, str(e))) return None
class ProductIniParser: def __init__(self): self.config_parser = ConfigParser() self.ini_file_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'product_svn_relationship.ini') self.config_parser.read(self.ini_file_path) def get_product_info_list(self): product_section_list = self.config_parser.sections() product_info_list = [] for product_section in product_section_list: product_title = self.config_parser.get(product_section, 'title') product_svn_url = self.config_parser.get(product_section, 'svn_url') product_info = ProductInfo(product_title, product_svn_url) product_info_list.append(product_info) return product_info_list
def readConfFile(fp): conf = ConfigParser() conf.optionxform = str conf.readfp(fp) if 'CONFIGURATION' not in conf.sections(): raise Exception("No section CONFIGURATION found") for (i,v) in conf.items('CONFIGURATION'): if i not in Conf.confValues: raise Exception("Invalid option %s" % i) else: try: val = Conf.confValues[i]["get"](conf, 'CONFIGURATION', i) if "values" in Conf.confValues[i] and val not in Conf.confValues[i]["values"]: raise Exception("Invalid value for option %s" % (i)) if "multiple" in Conf.confValues[i] and Conf.confValues[i]["multiple"]: Conf.confValues[i]["value"].append(val) else: Conf.confValues[i]["value"] = val except Exception, e: raise Exception("Invalid value for option %s" % (i))
def import_plonegazette_subscribers(options, newsletter, old_uid): """ Import PloneGazette subsribers into a new EasyNewsletter instance """ log('Importing subscribers %s' % newsletter.absolute_url(1)) subscribers_ini = os.path.join(options.input_directory, '%s_plonegazette_subscribers' % old_uid) CP = ConfigParser() CP.read([subscribers_ini]) get = CP.get if newsletter.portal_type == 'EasyNewsletter': parent = newsletter else: parent = newsletter.aq_parent for section in CP.sections(): id_ = get(section, 'id') if not id_ in parent.objectIds(): parent.invokeFactory('ENLSubscriber', id=id_) subscriber = parent[id_] subscriber.setTitle(get(section, 'fullname')) subscriber.setFullname(get(section, 'fullname')) subscriber.setEmail(get(section, 'email'))