Search code examples
pythonpython-config

Create a config file to hold values like username password url in python behave


I'm trying to create a config that holds information such as username password etc.

I have created an ini file holding this:

[DEFAULT]
username: user
password: pass

I then have a config map class like:

import configparser

class ConfigSectionMap:
    def __init__(self):
        my_config_parser = configparser.ConfigParser()
        my_config_parser.read('inilocation')
        print(my_config_parser.default_section)

    def config_map(self, section):
        dict1 = {}
        options = self.my_config_parser.options(section)
        for option in options:
            try:
                dict1[option] = self.my_config_parser.get(section, option)
                if dict1[option] == -1:
                    print("skip: %s" % option)
            except:
                print("exception on %s!" % option)
                dict1[option] = None
        return dict1

In my main class where I want to use this I do:

from config_section_map import ConfigSectionMap

print(ConfigSectionMap.config_map(("DEFAULT")['password']))

when running this I receive an error:

TypeError: string indices must be integers

I've been following the docs but it's not working: https://wiki.python.org/moin/ConfigParserExamples

Or if there is an easier way please show me

edit:

changing to this

print(ConfigSectionMap.config_map("DEFAULT")['password']) 

shows

TypeError: config_map() missing 1 required positional argument: 'section'

Solution

  • To give another answer the last part of your question Or if there is an easier way please show me

    OPTION1 = 'test'
    

    save it in config.py

    in code

    import config
    getattr(config, 'OPTION1', 'default value if not found')