简体   繁体   English

Python 导出环境变量时抛出 KeyError

[英]Python throws KeyError when exporting environment variables

I have a weird case where i have a secret.env file where i set all my environment variables as such:我有一个奇怪的情况,我有一个 secret.env 文件,我在其中设置了所有环境变量:

secret.env秘密.env

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

Then i built a docker file to export all the variables and run the app as such:然后我构建了一个 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"]

However, this is throwing a key error:但是,这引发了一个关键错误:

$ 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'

When i run this on my windows, it works fine!当我在我的 windows 上运行它时,它工作正常!

Can someone please help me on this?有人可以帮我吗?

You can use docker run --env-file secret.env... to set environment variables at runtime.您可以使用docker run --env-file secret.env...在运行时设置环境变量。 See the docker run documentation for more info.有关详细信息,请参阅docker run文档。

Sourcing a file in one RUN command will not persist after that RUN exits.RUN退出后,在一个RUN命令中获取文件将不会持续存在。 You also should not store secrets in the Docker image.您也不应该在 Docker 映像中存储机密。 It is more safe to leave them out at build time and to apply them at runtime.在构建时将它们排除在外并在运行时应用它们更安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM