您的位置:首页 > 其它

FastAPI踩坑----加载.env文件中的变量,有中文注释或者中文字符串报错

2020-07-18 05:01 381 查看

‘gbk’ codec can’t decode byte 0xad in position 178: illegal multibyte sequence

问题原因:

python-dotenv读取.env文件时,没有使用utf-8编码

解决办法:

通过查看源代码,我的办法是重写DoEnv的的——get_stream方法,在运行时加载,覆盖原来的代码

以下是我的实现代码:

logger = logging.getLogger(__name__)

def my_get_stream(self):
"""重写python-dotenv读取文件的方法,使用utf-8,支持读取中文"""
if isinstance(self.dotenv_path, StringIO):
yield self.dotenv_path
elif os.path.isfile(self.dotenv_path):
with io.open(self.dotenv_path, encoding='utf-8') as stream:
yield stream
else:
if self.verbose:
logger.warning("File doesn't exist %s", self.dotenv_path)
yield StringIO('')

DotEnv._get_stream = contextmanager(my_get_stream)

ps:emmm。。。总算可以在配置文件中写中文了,别问我为什么写中文。。。哈哈

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐