What is the use of python-dotenv?

后端 未结 2 2029
旧巷少年郎
旧巷少年郎 2020-12-23 13:34

Need an example and please explain me the purpose of python-dotenv.
I am kind of confused with the documentation.

相关标签:
2条回答
  • 2020-12-23 14:05

    In addition to @Will's answer, the python-dotenv module comes with a find_dotenv() that will try to find the .env file.

    # settings.py
    import os
    from dotenv import load_dotenv, find_dotenv
    
    load_dotenv(find_dotenv())
    
    SECRET_KEY = os.environ.get("SECRET_KEY")
    DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD")
    
    0 讨论(0)
  • 2020-12-23 14:13

    From the Github page:

    Reads the key,value pair from .env and adds them to environment variable. It is great of managing app settings during development and in production using 12-factor principles.

    Assuming you have created the .env file along-side your settings module.

    .
    ├── .env
    └── settings.py
    

    Add the following code to your settings.py

    # settings.py
    import os
    from os.path import join, dirname
    from dotenv import load_dotenv
    
    dotenv_path = join(dirname(__file__), '.env')
    load_dotenv(dotenv_path)
    
    SECRET_KEY = os.environ.get("SECRET_KEY")
    DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD")
    

    .env is a simple text file. With each environment variables listed per line, in the format of KEY="Value", lines starting with # is ignored.

    SOME_VAR=someval
    # I am a comment and that is OK
    FOO="BAR"
    
    0 讨论(0)
提交回复
热议问题