我正在为 Flask 寻找类似uWSGI + django autoreload 模式的东西。
7 回答
我正在运行 uwsgi 版本 1.9.5 和选项
uwsgi --py-autoreload 1
效果很好
如果您uwsgi
使用命令参数进行配置,请传递--py-autoreload=1
:
uwsgi --py-autoreload=1
如果您使用.ini
文件来配置uwsgi
和使用uwsgi --ini
,请将以下内容添加到您的.ini
文件中:
py-autoreload = 1
对于开发环境,您可以尝试使用 --python-autoreload uwsgi 的参数。查看源代码它可能仅在线程模式下工作(--enable-threads)。
您可以尝试使用 supervisord 作为您的 Uwsgi 应用程序的管理器。它还具有监视功能,可在文件或文件夹被“触摸”/修改时自动重新加载进程。
你会在这里找到一个很好的教程:Flask+NginX+Uwsgi+Supervisord
开发模式 Flask 的自动重新加载功能实际上是由底层 Werkzeug 库提供的。相关代码在werkzeug/serving.py
——值得一看。但基本上,主应用程序将 WSGI 服务器作为子进程生成,该子进程.py
每秒对每个活动文件进行一次统计,以查找更改。如果它看到任何内容,则子进程退出,并且父进程再次启动它 - 实际上是重新加载 chages。
没有理由不能在 uWSGI 层实现类似的技术。如果您不想使用 stat 循环,可以尝试使用底层 OS 文件监视命令。显然(根据 Werkzeug 的代码),pyinotify有问题,但也许Watchdog有效?尝试一些事情,看看会发生什么。
编辑:
作为对评论的回应,我认为这很容易重新实现。以您的链接提供的示例为基础,以及以下代码werkzeug/serving.py
:
""" NOTE: _iter_module_files() and check_for_modifications() are both
copied from Werkzeug code. Include appropriate attribution if
actually used in a project. """
import uwsgi
from uwsgidecorators import timer
import sys
import os
def _iter_module_files():
for module in sys.modules.values():
filename = getattr(module, '__file__', None)
if filename:
old = None
while not os.path.isfile(filename):
old = filename
filename = os.path.dirname(filename)
if filename == old:
break
else:
if filename[-4:] in ('.pyc', '.pyo'):
filename = filename[:-1]
yield filename
@timer(3)
def check_for_modifications():
# Function-static variable... you could make this global, or whatever
mtimes = check_for_modifications.mtimes
for filename in _iter_module_files():
try:
mtime = os.stat(filename).st_mtime
except OSError:
continue
old_time = mtimes.get(filename)
if old_time is None:
mtimes[filename] = mtime
continue
elif mtime > old_time:
uwsgi.reload()
return
check_for_modifications.mtimes = {} # init static
它未经测试,但应该可以工作。
import gevent.wsgi
import werkzeug.serving
@werkzeug.serving.run_with_reloader
def runServer():
gevent.wsgi.WSGIServer(('', 5000), app).serve_forever()
(你可以使用任意的 WSGI 服务器)
恐怕 Flask 实在是太简单了,无法默认捆绑这样的实现。
在生产中动态重新加载代码通常是一件坏事,但如果您关心开发环境,请查看这个 bash shell 脚本http://aplawrence.com/Unixart/watchdir.html
只需将睡眠间隔更改为适合您需要的任何内容,并将 echo 命令替换为您用于重新加载 uwsgi 的任何内容。我运行 uwsgi un master 模式并发送 killall uwsgi 命令。