Reading YAML file with Python results in AttributeError

There are 2 issues:

  • As others have said, yaml.load() loads associative arrays as mappings, so you need to use config['DB_NAME'].
  • The syntax in your config file is not correct: in YAML, keys are separated from values by a colon+space.

Should work if the file is formatted like this:

DB_HOST: 'localhost'
DB_USER: 'root'
DB_USER_PASSWORD: 'P@$$w0rd'
DB_NAME: 'moodle_data'
BACKUP_PATH: '/var/lib/mysql/moodle_data'

To backup your data base, you should be able to export it as a .sql file. If you're using a specific interface, look for Export.

Then, for Python's yaml parser.

DB_HOST :'localhost'
DB_USER : 'root'
DB_USER_PASSWORD:'P@$$w0rd'
DB_NAME : 'moodle_data'
BACKUP_PATH : '/var/lib/mysql/moodle_data'

is a key-value thing (sorry, didn't find a better word for that one). In certain langage (such as PHP I think), they are converted to objects. In python though, they are converted to dicts (yaml parser does it, JSON parser too).

# access an object's attribute
my_obj.attribute = 'something cool'
my_obj.attribute # something cool
del my_obj.attribute
my_obj.attribute # error

# access a dict's key's value
my_dict = {}
my_dict['hello'] = 'world!'
my_dict['hello'] # world!
del my_dict['hello']
my_dict['hello'] # error

So, that's a really quick presentation of dicts, but that should you get you going (run help(dict), and/or have a look here you won't regret it)

In your case:

config['DB_NAME'] # moodle_data

Tags:

Python

Yaml