Connect to dynamic database parameters sqlalchemy
Question: I am using sqlalchemy to connect to my database for my python API like so:

    
    
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbname'
    

My problem is that other developers in this project have different database
username/passwords. Whenever we push pull with git we have to reset the values
to accommodate the developers database. Is there a way we can have sqlalchemy
pull from a file? This way we could just add it to .gitignore.

Or is there an easier way to achieve this?


Answer: You want to set an environment variable for this. Since each environment is
unique to the machine it's running on, each team member will have their own
connection string picked up from their respective environment. I'll show an
example for Zsh shell, but Bash or other shells should be equivalent.

Create a file (if one doesn't exist already) called ~/.zshenv

In this file, add the line:

    
    
    export DB_CONNECTION_STRING="mysql://username:password@localhost/dbname"
    

Note that there should be **no spaces** between the variable definition and
its value (namely the equal sign has no spaces around it). This was an issue
for me on Zsh.

To apply this variable run `source ~/.zshenv`. It will automatically load on restart, but we don't want to logout/login every time when changing an environment varialble. Verify the variable was defined by running `printenv | grep DB_CONNECTION_STRING`.

In flask, simply define the following (remembering to `import os` on top):

    
    
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_CONNECTION_STRING')
    

_Using environment variables is really the way to go_. I used to hard-code
stuff, which is bad practice and as you can see, would be a problem for even
something trivial like multiple users connecting to the same database.

**EDIT** : please see @rmn's comment about instance folder flask
functionality; seems like a solid alternative to environment variables (of
course, this is limited to the Flask application, environment variables can be
used for anything)

