如何为FastAPI项目模板Cookiecutter实现.env配置的条件式提示?
要实现用户选择是否配置.env文件的条件式交互,Cookiecutter 1.7及以上版本支持通过_when字段定义变量的显示条件。以下是完整的cookiecutter.json配置:
{ "project_slug": "my_fastapi_project", "project_name": "My FastApi App", "author": "", "prefix": "", "version": "0.1.0", "add_env_file": ["yes", "no"], "database_url": { "default": "postgresql://user:password@localhost/dbname", "_when": "add_env_file == 'yes'" }, "secret_key": { "default": "", "_when": "add_env_file == 'yes'" }, "api_port": { "default": "8000", "_when": "add_env_file == 'yes'" } }
关键说明
- 修正了原字段名
add .env file为add_env_file,避免空格引发的潜在问题,符合变量命名规范。 - 为每个.env相关变量添加
_when字段,设置判断条件add_env_file == 'yes',只有用户选择添加.env文件时,才会触发这些变量的输入提示。 - 可根据项目需求扩展更多.env变量,只需为新增变量配置对应的
_when条件即可。
内容的提问来源于stack exchange,提问作者firas boukhchim
相关产品推荐
相关产品推荐

