Sam Munroe
Sam Munroe

Reputation: 1418

Connect to dynamic database parameters sqlalchemy

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?

Upvotes: 2

Views: 6107

Answers (2)

Borys Serebrov
Borys Serebrov

Reputation: 16172

Alternative approach - each developer can have local settings in the file ignored by git, for example, local_config.py.

Then you use it like this:

try:
    import local_config
    app.config['SQLALCHEMY_DATABASE_URI'] = local_config.DB_URI
except ImportError:
    print "No Local config, use defaults"
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbname'

This can be useful if there are many parameters to set.

You can keep something like local_config.py.example in the repository where all the parameters are listed. Then everyone can rename it to the local_config.py and customize the parameters.

Upvotes: 0

GG_Python
GG_Python

Reputation: 3541

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)

Upvotes: 3

Related Questions