簡體   English   中英

Python 導出環境變量時拋出 KeyError

[英]Python throws KeyError when exporting environment variables

我有一個奇怪的情況,我有一個 secret.env 文件,我在其中設置了所有環境變量:

秘密.env

export TWITTER_CONSUMER_KEY="something"
export TWITTER_CONSUMER_SECRET="something"

然后我構建了一個 docker 文件來導出所有變量並運行應用程序:

FROM python:3.8-slim-buster

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Install the dependencies
RUN pip install -r requirements.txt

RUN find . -name \*.pyc -delete

# Export all variables
RUN /bin/bash -c "source secret.env";

# tell the port number the container should expose
EXPOSE 8083

# run the command
ENTRYPOINT ["python", "run.py"]

但是,這引發了一個關鍵錯誤:

$ docker run --name fortweet --rm -i -t fortweet:latest bash
Traceback (most recent call last):
  File "run.py", line 1, in <module>
    from app import socketio, app
  File "/app/app/__init__.py", line 65, in <module>
    app = create_app()
  File "/app/app/__init__.py", line 38, in create_app
    my_settings = settings.TwitterSettings.get_instance()
  File "/app/app/setup/settings.py", line 47, in get_instance
    TwitterSettings()
  File "/app/app/setup/settings.py", line 14, in __init__
    self.consumer_key = os.environ["TWITTER_CONSUMER_KEY"]
  File "/usr/local/lib/python3.8/os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'TWITTER_CONSUMER_KEY'

當我在我的 windows 上運行它時,它工作正常!

有人可以幫我嗎?

您可以使用docker run --env-file secret.env...在運行時設置環境變量。 有關詳細信息,請參閱docker run文檔。

RUN退出后,在一個RUN命令中獲取文件將不會持續存在。 您也不應該在 Docker 映像中存儲機密。 在構建時將它們排除在外並在運行時應用它們更安全。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM