代码之家  ›  专栏  ›  技术社区  ›  Milano

Django(Gunicorn)没有看到ENV VARS在生产,但“shell”看到了

  •  0
  • Milano  · 技术社区  · 4 年前

    我在这里非常绝望。我不明白为什么 Django 看不到环境变量,即使 shell 可以

    在里面 设置.py

    BASE_URL = os.getenv('VUE_APP_WEB_URL','http://127.0.0.1:8080/')
    

    在里面 admin.py

    class _UserAdmin...
        ...
        list_display = ('username', 'email', 'is_staff', '_set_pwd_url','base_url')
        list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
    
        def base_url(self, obj: User):
            return settings.BASE_URL
    

    在里面 /etc/环境

    VUE_APP_WEB_URL=http://my.url.xyz/
    

    服务器已多次重新启动,而且 Gunicorn 已由重新启动 sudo service gunicorn restart

    enter image description here

    它仍然显示默认值,而不是ENV VAR。

    现在,当我在中测试时 django shell :

    Python 3.8.10 (default, Sep 28 2021, 16:10:42) 
    [GCC 9.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> settings.BASE_URL
    'http://my.url.xyz/'
    >>> 
    

    发生了什么事?

    附言:浏览器缓存不是问题所在。

    0 回复  |  直到 4 年前
        1
  •  0
  •   Cl0ud-l3ss    4 年前

    制作一个 .env 文件(最好是根目录),然后配置 gunicorn.service 配置以指向该文件。

    制作一个 .env 文件

    VUE_APP_WEB_URL= 'http://my.url.xyz/'
    ANOTHER_VARIABLE = 'something'
    

    然后添加 EnvironmentFile 到您的配置

    ...
    
    [Service]  
    ...
    EnvironmentFile=/path/to/your/.env
    ExecStart=
    ...            
    

    您也可以使用 pip install django-dotenv 它还将查找.env并对其进行初始化。

    推荐文章