Google App Engine and Python: a correct way to store configuration variables

When you develop an application, often you could need to store some configurations. This data can contain a lot of sensitive informations, and this is a critical point if your sourcecode is hosted on a GitHub repository.

In fact, a lot of unwanted dataleaks starts with a commit that contains accidentally a configuration file, and a lot of simple tools developed for search this leaks are available (such us gittyleaks).

So, is my opinion that, also in development stage, a good practice should be to store configuration data into a database/datastore.

Recently i’ve worked on a telegram bot, hosted on Google App Engine and developed in Python.

A basic practice to store configuration data may be to store that on app.yaml as environment variables, in this way:

env_variables:
   TELEGRAM_TOKEN: 'YOUR TOKEN'

Then these variables will be available in the os.environ dictionary.

But, like I said, in not a good method in terms of security, and storing configurations into a datastore should be a better practice.

Below the brief code snippet i use for storing configurations:

from google.appengine.ext import ndb

class Settings(ndb.Model):
  name = ndb.StringProperty()
  value = ndb.StringProperty()

  @staticmethod
  def get(name):
    NOT_SET_VALUE = "NOT SET"
    retval = Settings.query(Settings.name == name).get()
    if not retval:
      retval = Settings()
      retval.name = name
      retval.value = NOT_SET_VALUE
      retval.put()
    return retval.value

Your application would do this to get a value:

TELEGRAM_TOKEN = Settings.get('TELEGRAM_TOKEN')

If there is a value for that key in the datastore, you will get it.
If there isn’t, a placeholder record will be created: simply go to the Developers Console and update the placeholder record.

That’s all folks!


References and further readings

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.