best way to read in values from config file (YAML) -- python
I have the following function that reads in data from a YAML file:
import yaml def read_yaml(): """ reads a yaml file and returns tuple with configuration data for HTTP requests :return tuple: (doc, base_url, headers) """ with open("yaml/okta_yaml.yaml", 'r') as f: doc = yaml.safe_load(f) base_url = doc["connection"]["base_url"] headers = doc["connection"]["headers"] ss_username = doc["secret_server"]["username"] ss_password = doc["secret_server"]["password"] ss_url = doc["secret_server"]["url"] ss_domain = doc["secret_server"]["domain"] return doc, base_url, headers, ss_username, ss_password, ss_url, ss_domain
To pull in a subset of the returned tuple from the function above into a different module I have something like the following:
import requests from read import read_yaml def find_userid(username): """ performs HTTP GET request to retrieve Okta user id :param str username: username retrieved by main.py argument :return str userid: okta userid """ # unpacks variables from the read_yaml function doc, base_url, headers = read_yaml()[0:3] # builds full HTTP GET url url = base_url + '/api/v1/users?q=' + username # runs the HTTP GET request response = requests.get(url, headers=headers) # encodes HTTP response into JSON format for processing data = response.json() # iterate through JSON response and find 'id' value for user in data: userid = user['id'] if userid: print "### Found userid: " + userid + " ###" else: print "### Could not find specified user ###" # return userid string return userid def deactivate_okta(userid): """ performs HTTP POST request to disable Okta user based on userid :param str userid: string value returned from find_userid() function """ # unpacks variables from the read_yaml function doc, base_url, headers, = read_yaml()[0:3] # builds full POST url url = base_url + '/api/v1/users/' + userid + '/lifecycle/deactivate' # runs HTTP POST request to deactivate user based on user id response = requests.post(url, headers=headers) # return code 200 means POST successful if response.status_code == 200: print '### User deactivated ###' else: print '### Unable to deactivate user ###' + userid
Everything works, but I'm wondering what is the best way to read the YAML file and grab the data I need and to inject it into another function/module. The reason for this is, the current read_yaml() function returns a tuple with a lot of values and as is, it only serves two apps I'm trying to access via the API.
I have about 15 other apps that I want access via the api and I don't think it's the most efficient way to keep adding return values in the read_yaml() function.
This is my first attempt at some python code so I'm probably doing a lot of things wrong and could use some help on how to best approach this.