我的serverless.yml文件看起来像这样:
environment:
IS_OFFLINE: False
DYNAMODB_TABLE: ${self:service}-${opt:stage, self:provider.stage}
iamRoleStatements: ${file(config/iam.yml)}
但是,当我尝试计算IS_OFFLINE
变量时,它会将其解析为字符串,从而使值真实,尽管它是用False
>>>> print(os.environ.get('IS_OFFLINE'))
'IS_OFFLINE': 'false'
如果可能的话,如果有另一种方法来配置 .yml 文件,我宁愿避免这种类型的条件(在所有语言的 Python 中(。
if os.environ.get('IS_OFFLINE') == "true":
在 2021 年,serverless.yml
中的true
/false
变量仍然在 Python 中转换为'true'
/'false'
字符串。 您可以使用distutils.util
中的strtobool
安全地解析它们:
from distutils.util import strtobool
if strtobool(environ.get("MY_VAR")):
这比字符串比较干净一些,适用于许多真/假同义词,如是/否、1/0、开/关。见 https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool
一个未定义的变量的计算结果为False
:
from distutils.util import strtobool
if strtobool(environ.get("MY_UNDEFINED_VAR")):
# this will NOT be executed
print('var is undefined')