Search code examples
ajaxdjangomongodbmlab

where to store api key in Django


I currently build web app which is using external MongoDb via Mongolabs. The api is based on personal key using in urls. As docs says e.g.:

Here’s an example of a complete Resource URL:

https://api.mongolab.com/api/1/databases?apiKey=**2E81PUmPFI84t7UIc_5YdldAp1ruUPKye** So the question is how to securely store such api key 2E81PUmPFI84t7UIc_5YdldAp1ruUPKye

Reading Django docs about Cross Site Request Forgery but stil do not understand where the key is recorded.


Solution

  • There are two ways to do this.

    One way is to have a local_settings.py file that's imported in the main settings.py file and put into .gitignore so it's not in git. Some people however think this isn't good practice, because it might tempt to put complex things in there that aren't in VCS, so people effectively have different environments. I however am fine with it.

    try:
        from local_settings import *
    except ImportError:
        pass  # No local_settings file
    

    The other way (recommended by dislikers of the first way) is by setting it via environment variables, and reading these in settings.py.

    MONGO_API_KEY = os.environ['MONGO_API_KEY']
    

    You'd then have to pass the environment variable somehow though. E.g. via uwsgi's environ setting, or by setting it in your bash with export, or via another way.