FOSSASIA‘s Open Event Server uses some environment variables to maintain different configuration for different deployment. However one con of it was, for local development, developers have to run many export commands.
It all started with the “It is not convenient, we humans are lazy.” phrase. A recent suggestion was to read this environment variables with files rather than running commands every time.
This few example environment variable commands were:
Open Event Server now uses .env file and envparse to handle this.
The changes were:
- We store the variables in .env file, let it get ignored by git, and
- Use envparse to parse the file.
What is envpase:
envparse is a simple utility to parse environment variables. It aims to eliminate duplicated, often inconsistent parsing code and instead provide a single, easy-to-use wrapper.
So instead of reading the string from the command line everytime:
We read it from the file:
To read from command line we had:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', None)
Which now was parsed using envparse as:
SQLALCHEMY_DATABASE_URI = env('DATABASE_URL', default=None)
In the above example, DATABASE_URL is a string and we store this string in SQLALCHEMY, setting the default by the default parameter(None in this case).
The type of environment variable is originally string, we can simply use env to parse these strings. For simplicity and understanding we can also use env.str. For different types, we can simply type cast them like env.bool (for boolean), env.int (for integer) etc. One good advantage of this envparse feature is the direct use of these type cast rather than checking for strings (i.e. reading the string from command line).
For example, earlier we had something like this:
socketio_integration = os.environ.get('INTEGRATE_SOCKETIO’)
if socketio_integration == true’:
Using envparse, we can have something like this:
INTEGRATE_SOCKETIO = env.bool('INTEGRATE_SOCKETIO’, default=False)
This helps in parsing as boolean instead of string. So, if we have INTEGRATE_SOCKETIO=true in .env file, we can write INTEGRATE_SOCKETIO = env.bool(‘INTEGRATE_SOCKETIO’, default=False). This automatically converts the true to boolean True in python.
In order to use envparse we install envparse with:
In the case of Open Event Server project, you only have to install the requirements.txt and copy the .env.example already mentioned in installation doc.
This is how we finally remove the headache of writing big exports again and again and fairly helps beginners to start off with Open Event Server project much more easily and quickly.