问题描述
我想通过Apache + mod_wsgi传递环境变量,以告诉我的应用程序是在开发环境还是生产环境中运行. (这需要在启动应用程序时发生,然后再发出任何请求.)例如:
I want to pass in environment variables through Apache + mod_wsgi to tell my app whether it's running in a development or production environment. (This needs to happen when the app is launched, before any requests have come in.) For example:
<VirtualHost *:80>
...
SetEnv ENVTYPE production
WSGIScriptAlias /myapp /apps/www/80/wsgi-scripts/myapp/run.py
</VirtualHost>
<VirtualHost *:8080>
...
SetEnv ENVTYPE development
WSGIScriptAlias /myapp /apps/www/80/wsgi-scripts/myapp/run.py
</VirtualHost>
基于对"> Apache SetEnv无效的回答如对mod_wsgi 所期望的那样,我已经设置了run.py
和主__init__.py
,如下所示:
Based on the answer given to "Apache SetEnv not working as expected with mod_wsgi", I have setup run.py
and the main __init__.py
like this:
from myapp import app as application
if __name__ == '__main__':
application.run(debug=True, threaded=True)
新run.py:
import os
from myapp import app as _application
def application(environ, start_response):
os.environ['ENVTYPE'] = environ['ENVTYPE']
return _application(environ, start_response)
if __name__ == '__main__':
_application.run(debug=True, threaded=True)
__ init __.py
app = Flask(__name__)
app.config.from_object(__name__)
if os.environ.get('ENVTYPE') == 'production'
# Setup DB and other stuff for prod environment
else:
# Setup DB and other stuff for dev environment
两个问题
-
这实际上不起作用.在
__init__.py
中,在os.envrion
中没有"ENVTYPE"键.为什么不呢?
This does not actually work. Within
__init__.py
, there is no 'ENVTYPE' key inos.envrion
. Why not?
我也不知道如何修复if __name__ == '__main__'
部分,以便可以在PC上将run.py
作为本地Flask应用程序运行.我在新的run.py
中添加的内容有效,但只能通过调用_application
而不是包装函数application
来实现.结果,_application
无法访问我定义的环境变量.我该如何解决?
I also don't know how to fix the if __name__ == '__main__'
section so that I can run run.py
as a local Flask app on my PC. What I put in my new run.py
works, but only by calling _application
instead of the wrapper function application
. As a result _application
doesn't have access to the environment variables I defined. How can I fix that line?
谢谢!
推荐答案
由于此提示
所以run.py
的工作版本是:
import os
def application(environ, start_response):
os.environ['ENVTYPE'] = environ['ENVTYPE']
from myapp import app as _application
return _application(environ, start_response)
if __name__ == '__main__':
_application.run(debug=True, threaded=True)
我仍然没有解决问题2,但是-我不知道如何直接调用程序(if __name__ == '__main__'
)并可以访问ENVTYPE环境变量.建议仍将不胜感激.也许我将把这个问题分解成自己的StackOverflow问题.
I still haven't solved problem #2, however - I don't know how to call the program directly (if __name__ == '__main__'
) and have access to the ENVTYPE environment variable. Suggestions would still be appreciated. Maybe I'll break that issues out into its own StackOverflow question.
这篇关于Flask为什么看不到来自Apache(mod_wsgi)的环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!