Search code examples
pythonflaskpycharm

PyCharm Flask configuration uses the wrong folder as working directory?


For no apparent reason, Flask decided to use a folder one level above the actual project directory.

Project details:

  • Working directory in Run/Debug is set correctly
  • Python console in PyCharm starts in the correct directory
  • The parent folder is mentioned once -- in the "Paths to .env files" field, where a single .env file is included
  • Settings -> Project: projectname -> Project Structure shows the correct structure (intended working directory is set as project root)
  • Just in case, I set the working directory for both Python and Flask consoles in Settings -> Build, Execution, Deployment -> Console to project root

Despite the working directory being set in every place I could think of, when I try to use the project, I get an error because it tried to load a file from the parent directory (e. g. ~/file.yml instead of ~/projectname/file.yml).

Running the project manually via the default Python configuration with the same working directory and env file path settings works fine.

What am I missing?


Solution

  • I've recently made a shell script to run this project separately, and I've ran into a similar issue: when running in debug mode, the same error occurs on "Restarting with stat" specifically, the initial run is fine. This made me think it's an issue with Flask or Python, not with PyCharm.

    After trying out answers from this StackOverflow thread to run the app by providing the full path instead of a relative one, I noticed the error now happened when opening some file in the beginning of the setup.

    I reworded my question slightly and came upon this GitHub discussion, in which a Flask maintainer says load_dotenv silently changing working directories if it happens to open a file when starting is intended behavior of load_dotenv. Complete lunacy, but what do I know.

    Solution

    Use FLASK_SKIP_DOTENV=1 and load all env variables either via

    set -o allexport
    source path/to/extra/.env
    set +o allexport
    

    if using a shell script like I did or manual load_dotenv() calls inside your app (or both).