Search code examples
pythonmacospipdotenv

Adding Python library to Flask app requirements.txt


Long time Java dev who inherited a Python (Flask) application that is in dire need of some maintenance. Instead of using env vars or system properties or any kind of configuration (!!!) all the connections and credentials are hardcoded right there in the source code. Yikes.

Trying to get python-dotenv loaded and used. So I tried to install it using pip3 (I'm on a Mac):


myuser@mymac my-database-service % pip3 install python-dotenv

Defaulting to user installation because normal site-packages is not writeable
Collecting python-dotenv
  Downloading python_dotenv-0.21.1-py3-none-any.whl (19 kB)
Installing collected packages: python-dotenv
  WARNING: The script dotenv is installed in '/Users/myuser/Library/Python/3.8/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed python-dotenv-0.21.1
WARNING: You are using pip version 20.2.3; however, version 23.0 is available.
You should consider upgrading via the '/Library/Developer/CommandLineTools/usr/bin/python3 -m pip install --upgrade pip' command.

Looks like it succeeded however I don't see anything changed in my project. Nothing added, no new folders, etc.

Do I now just manually add python-dotenv-0.21.1 to my requirements.txt? Can someone explain it like I'm five (ELIF) and help this old Java dog out getting python-dotenv properly installed and usable inside my project?


Solution

  • Yes that's correct - installing the requirement just installs it in your current environment. The next steps would be:

    1. At this point, you should be able to use the package locally. If you want to track the dependency to be installable in the future (e.g you create a new local environment, another developer installs the repo, etc.), manually add a new line in your requirements.txt file. You can run pip freeze | grep dotenv to grab the exact line to add to requirements. It should look something like python-dotenv==0.21.1. Then future runs of pip3 install -r requirements.txt will install dotenv as well.

    2. Create a .env file in the root directory of your repository and update it with the environment you want to use. The format of this file mimics bash, e.g:

    DATABASE_URL=val
    
    1. In your Flask function that runs your server, add:
    from dotenv import load_dotenv
    load_dotenv()
    

    This will load the configuration from the .env file and make it accessible in your repository. You can then access your environment like you would any environment variable:

    import os
    os.environ.get("env_variable_name")