将Flask env var添加到virtualenv的激活脚本中可以吗? [英] Is adding Flask env vars to the virtualenv's activate script OK?

查看:94
本文介绍了将Flask env var添加到virtualenv的激活脚本中可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在virtualenv中进行Flask项目.每次启动新终端时,都必须重新初始化以下Flask环境变量:

I'm working on my Flask project in a virtualenv. Every time I start a new terminal, I have to reinitialize these Flask environment variables:

export FLASK_APP="server.py"
export FLASK_DEBUG="1"

我的目标是不必手动输入.

My goal is to not have to type them in manually.

我试图编写一个设置它们的Python脚本,但无法使其正常工作.我尝试编写一个设置它们的shell脚本,但是Flask会引发一个错误,提示我的Python路径不正确.

I tried writing a Python script that set them, but couldn't make it work. I tried writing a shell script that set them, but Flask would raise an error that said my Python path was incorrect.

最后,我尝试将env vars添加到virtualenv的activate脚本的底部.有效!设置环境变量,并且Flask按预期运行.

Finally, I tried adding the the env vars to the bottom of the virtualenv's activate script. It worked! The env vars are set and Flask runs as expected.

$ source venv/bin/activate
$ flask run

可以像这样修改activate脚本吗?这只是出于开发目的.

Is it OK to modify the activate script like this? This is just for development purposes.

推荐答案

是的,在virtualenv的activate脚本中设置环境变量非常适合管理您的开发环境. 在Flask的文档中进行了说明.仅当env已在终端中激活,创建新的env时必须记住要添加它们,但是这没什么问题.

Yes, setting environment variables in the virtualenv's activate script is fine for managing your development environment. It's described in Flask's docs. They're only active when the env is activated in the terminal, and you have to remember to add them if you create a new env, but there's nothing wrong with it.

在Flask 1.0中,您可以使用dotenv文件代替.安装python-dotenv:

With Flask 1.0, you can use dotenv files instead. Install python-dotenv:

pip install python-dotenv

添加.flaskenv文件:

FLASK_APP=server

flask命令将在运行命令时自动设置它们:

And the flask command will automatically set them when running a command:

flask run

与venv混淆相比,此方法的优势在于您可以提交此文件,以便将其应用于您在代码上工作的任何地方.

The advantage of this over messing with the venv is that you can commit this file so it applies anywhere you work on the code.

这篇关于将Flask env var添加到virtualenv的激活脚本中可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆