Manage application configuration with json file

user_scerets_with_config_json

Skill - Managing application configuration and sensitive data using a JSON file in a python script / project

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


It is not advisable to keep application configuration or sensitive data like usernames , passwords, api keys, port numbers in the source code or hard-code them in our code. The reasons not to do so is

  • You have to change and re-deploy the code once the usernames, passwords change
  • We can accidentally commit our code to open source repositories like GitHub etc., where our sensitive data will be exposed

One of the easy ways to maintain sensitive data is using JSON file as application configuration file.
The advantages of storing application configuration in a JSON file is

  • Data is not hard-coded in the application code. Hence no need to change code when usernames, passwords, port numbers change
  • If mentioned in .gitignore file, the config JSON file will not be pushed to source control like git

Sample config.json file

{
"username": "john",
"password": "superSecret",
"port": 80
}

simple scenario with only one script file

# import json module
import json
def loadAppConfig(fName="config.json"):
    with open(fName) as f:
        global appConf
        appConf = json.load(f)
        return appConf

# load config data from json file
# and store in a variable
appConf = loadAppConfig()

# use this appConf object in your script
print(appConf)
print('username is {0}'.format(appConf['username']))
print('password is {0}'.format(appConf['password']))

caching config file data to prevent multiple JSON file reads

create a python file by name appConfig.py in the same folder as that of config.json

# appConfig.py

# import json module
import json

# initialize the app config global variable
appConf = {}

# load config json into the global variable
def loadAppConfig(fName="config.json"):
    with open(fName) as f:
        global appConf
        appConf = json.load(f)
        return appConf

# get the cached application config object
def getAppConfig():
    global appConf
    return appConf

Using app config data in the script

### index.py
# import the required functions from appConfig.py file
from appConfig import getAppConfig, loadAppConfig

# load app config data from json file
configDict = loadAppConfig()
print(configDict)

print("******************")

# using getAppConfig() to access config data
# after loading it once
print(getAppConfig())

Video

The video tutorial for this post can be found here

Online Interpreter

You can run these codes online at https://www.programiz.com/python-programming/online-compiler/ , https://repl.it/


References

Table of Contents

Comments