我在访问 python 应用程序的 init.py 文件中的 Kubernetes 环境变量时遇到问题。然而,它似乎在其他文件中可用。
我的 init.py 文件包含此代码 app.config.from_object(os.environ['APP_SETTINGS'])
。 APP_SETTINGS
的值取决于我的环境,值为 config.DevelopmentConfig
、config.StagingConfig
或 config.ProductionConfig
。从这里,我的应用程序从我的 config.py 文件中提取配置,如下所示:
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
WTF_CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'
APP_SETTINGS = os.environ['APP_SETTINGS'] # For debug purposes
class DevelopmentConfig(Config):
TEMPLATES_AUTO_RELOAD = True
DEBUG = True
class StagingConfig(Config):
DEBUG = True
class ProductionConfig(Config):
DEBUG = False
当我在 docker-compose 的开发环境中本地设置 APP_SETTINGS 时,就像这样......
environment:
- APP_SETTINGS=config.DevelopmentConfig
一切都很好。当我在 Secrets 文件中设置 APP_SETTINGS=config.StagingConfig
并将其部署到 Kubernetes 中的 Staging pod 时,出现以下错误:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 434, in import_string
return getattr(module, obj_name)
AttributeError: module 'config' has no attribute 'StagingConfig
'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 436, in import_string
raise ImportError(e)
ImportError: module 'config' has no attribute 'StagingConfig
'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 3, in <module>
from app import app
File "/root/app/__init__.py", line 11, in <module>
app.config.from_object(os.environ['APP_SETTINGS'])
File "/usr/local/lib/python3.6/site-packages/flask/config.py", line 168, in from_object
obj = import_string(obj)
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 443, in import_string
sys.exc_info()[2])
File "/usr/local/lib/python3.6/site-packages/werkzeug/_compat.py", line 137, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 436, in import_string
raise ImportError(e)
werkzeug.utils.ImportStringError: import_string() failed for 'config.StagingConfig\n'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Debugged import:
- 'config' found in '/root/config.py'.
- 'config.StagingConfig\n' not found.
Original exception:
ImportError: module 'config' has no attribute 'StagingConfig
'
upgrading database schema...
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 434, in import_string
return getattr(module, obj_name)
AttributeError: module 'config' has no attribute 'StagingConfig
'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 436, in import_string
raise ImportError(e)
ImportError: module 'config' has no attribute 'StagingConfig
'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 3, in <module>
from app import app
File "/root/app/__init__.py", line 11, in <module>
app.config.from_object(os.environ['APP_SETTINGS'])
File "/usr/local/lib/python3.6/site-packages/flask/config.py", line 168, in from_object
obj = import_string(obj)
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 443, in import_string
sys.exc_info()[2])
File "/usr/local/lib/python3.6/site-packages/werkzeug/_compat.py", line 137, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 436, in import_string
raise ImportError(e)
werkzeug.utils.ImportStringError: import_string() failed for 'config.StagingConfig\n'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Debugged import:
- 'config' found in '/root/config.py'.
- 'config.StagingConfig\n' not found.
Original exception:
ImportError: module 'config' has no attribute 'StagingConfig
'
starting metriculous web server...
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 434, in import_string
return getattr(module, obj_name)
AttributeError: module 'config' has no attribute 'StagingConfig
'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 436, in import_string
raise ImportError(e)
ImportError: module 'config' has no attribute 'StagingConfig
'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 3, in <module>
from app import app
File "/root/app/__init__.py", line 11, in <module>
app.config.from_object(os.environ['APP_SETTINGS'])
File "/usr/local/lib/python3.6/site-packages/flask/config.py", line 168, in from_object
obj = import_string(obj)
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 443, in import_string
sys.exc_info()[2])
File "/usr/local/lib/python3.6/site-packages/werkzeug/_compat.py", line 137, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.6/site-packages/werkzeug/utils.py", line 436, in import_string
raise ImportError(e)
werkzeug.utils.ImportStringError: import_string() failed for 'config.StagingConfig\n'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Debugged import:
- 'config' found in '/root/config.py'.
- 'config.StagingConfig\n' not found.
Original exception:
ImportError: module 'config' has no attribute 'StagingConfig
但是,当我像这样 app.config.from_object('config.StagingConfig')
在 init.py 文件中硬编码 APP_SETTINGS 值并部署到 Kubernetes 时,它工作正常。当我这样做时,我什至可以通过登录我的 pod 并运行 echo $APP_SETTINGS
来确认 Kubernetes 设置中声明的 APP_SETTINGS env var 是否存在。
对我做错了什么有什么想法吗?
编辑#1 - 添加我的deployment.yaml 文件
kind: Deployment
apiVersion: apps/v1beta2
metadata:
annotations:
deployment.kubernetes.io/revision: '4'
selfLink: /apis/apps/v1beta2/namespaces/tools/deployments/met-staging-myapp
resourceVersion: '51731234'
name: met-staging-myapp
uid: g1fce905-1234-56y4-9c15-12de61100d0a
creationTimestamp: '2018-01-29T17:22:14Z'
generation: 6
namespace: tools
labels:
app: myapp
chart: myapp-1.0.1
heritage: Tiller
release: met-staging
spec:
replicas: 1
selector:
matchLabels:
app: myapp
release: met-staging
template:
metadata:
creationTimestamp: null
labels:
app: myapp
release: met-staging
spec:
containers:
- name: myapp-web
image: 'gitlab.ourdomain.com:4567/ourspace/myapp:web-latest'
ports:
- containerPort: 80
protocol: TCP
env:
- name: APP_SETTINGS
valueFrom:
secretKeyRef:
name: myapp-creds
key: APP_SETTINGS
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: myapp-creds
key: AWS_ACCESS_KEY_ID
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: myapp-creds
key: AWS_SECRET_ACCESS_KEY
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
imagePullPolicy: Always
- name: myapp-celery
image: 'gitlab.ourdomain.com:4567/ourspace/myapp:celery-latest'
env:
- name: APP_SETTINGS
valueFrom:
secretKeyRef:
name: myapp-creds
key: APP_SETTINGS
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: myapp-creds
key: AWS_ACCESS_KEY_ID
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: myapp-creds
key: AWS_SECRET_ACCESS_KEY
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
imagePullPolicy: Always
- name: rabbit
image: 'rabbitmq:alpine'
env:
- name: RABBITMQ_DEFAULT_USER
value: rabbit_user
- name: RABBITMQ_DEFAULT_PASS
value: fake_pw
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
imagePullPolicy: IfNotPresent
restartPolicy: Always
terminationGracePeriodSeconds: 30
dnsPolicy: ClusterFirst
securityContext: {}
imagePullSecrets:
- name: gitlab-registry
schedulerName: default-scheduler
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
revisionHistoryLimit: 10
progressDeadlineSeconds: 600
status:
observedGeneration: 6
replicas: 1
updatedReplicas: 1
readyReplicas: 1
availableReplicas: 1
conditions:
- type: Available
status: 'True'
lastUpdateTime: '2018-01-29T17:22:14Z'
lastTransitionTime: '2018-01-29T17:22:14Z'
reason: MinimumReplicasAvailable
message: Deployment has minimum availability.
- type: Progressing
status: 'True'
lastUpdateTime: '2018-05-25T10:20:49Z'
lastTransitionTime: '2018-02-16T20:29:45Z'
reason: NewReplicaSetAvailable
message: >-
ReplicaSet "met-staging-myapp-2615c4545f" has successfully
progressed.
最佳答案
werkzeug.utils.ImportStringError: import_string() failed for 'config.StagingConfig\n'. Possible reasons are:
它非常清楚地向您显示模块名称尾部有一个换行符,对于尝试 echo something | base64
的人来说,这是一个非常非常常见的错误并将该值放入 kubernetes Secret
。正确的方法是通过 kubectl create secret generic myapp-creds --from-literal=APP_SETTINGS=config.StagingConfig
,或printf '%s' config.StagingConfig | base64
。或者,当然,停止将非 secret 文本放入 secret 中并使用 ConfigMap
或者只是传统环境value: config.StagingConfig
设置,并保留Secret
构造 Secret
值。
关于python - 无法访问 Python 的 init.py 文件中的 Kubernetes env var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50530833/