[python]web框架中的代码自动重载怎么实现

在开发和调试wsgi应用程序时,有不少方法能够自动从新加载代码。例如,若是你使用的是werkzeug,则只须要传use_reloader参数便可:python

run_sumple('127.0.0.1', 5000, app, use_reloader=True)
复制代码

对于Flask,实际上在内部使用werkzeug,因此你须要设置debug = true:git

app.run(debug=True)
复制代码

django会在你修改任何代码的时候自动为你从新加载:github

python manage.py runserver
复制代码

全部这些例子在本地开发的时候都很是有用,可是,建议不要在实际生产中使用。shell

做为学习,能够一块儿来看一下,python是如何让代码自动地从新加载的?django

uWSGI

若是使用的是 uwsgidjango ,实际上能够直接经过代码跳转查看一下 django 自己的自动重载机制:vim

import uwsgi
from uwsgidecorators import timer
from django.utils import autoreload

@timer(3)
def change_code_gracefull_reload(sig):
    if autoreload.code_changed():
        uwsgi.reload()
复制代码

能够看出,django 经过一个定时器在不断的监测代码是否有变化,以此来出发从新加载函数。bash

若是你使用的是其余框架,或者根本没有框架,那么可能就须要在应用程序中本身来实现代码改动监测。这里是一个很好的示例代码,借用和修改自 cherrypyapp

import os, sys

_mtimes = {}
_win = (sys.platform == "win32")

_error_files = []

def code_changed():
    filenames = []
    for m in sys.modules.values():
        try:
            filenames.append(m.__file__)
        except AttributeError:
            pass
    for filename in filenames + _error_files:
        if not filename:
            continue
        if filename.endswith(".pyc") or filename.endswith(".pyo"):
            filename = filename[:-1]
        if filename.endswith("$py.class"):
            filename = filename[:-9] + ".py"
        if not os.path.exists(filename):
            continue # File might be in an egg, so it can't be reloaded.
        stat = os.stat(filename)
        mtime = stat.st_mtime
        if _win:
            mtime -= stat.st_ctime
        if filename not in _mtimes:
            _mtimes[filename] = mtime
            continue
        if mtime != _mtimes[filename]:
            _mtimes.clear()
            try:
                del _error_files[_error_files.index(filename)]
            except ValueError:
                pass
            return True
    return False
复制代码

你能够将上面的内容保存在你的项目中的 autoreload.py 中,而后咱们就能够像下面这样去调用它(相似于 django 的例子):框架

import uwsgi
from uwsgidecorators import timer
import autoreload

@timer(3)
def change_code_gracefull_reload(sig):
    if autoreload.code_changed():
        uwsgi.reload()
复制代码

gunicorn

对于 gunicorn ,咱们须要写一个脚原本 hook(钩子:触发)gunicorn 的配置中:ide

import threading
import time
try:
    from django.utils import autoreload
except ImportError:
    import autoreload

def reloader(server):
    while True:
        if autoreload.code_changed():
            server.reload()
        time.sleep(3)

def when_ready(server):
    t = threading.Thread(target=reloader, args=(server, ))
    t.daemon = True
    t.start()
复制代码

你须要把上面的代码保存到一个文件中,好比说 config.py ,而后像下面这样传给 gunicorn

gunicorn -c config.py application
复制代码

外部解决方法

你也能够经过正在使用的 wsgi 服务系统自己之外的一些方法来实现重启系统,它只需发出一个信号,告诉系统重启代码,好比可使用 watchdog。例如:

watchmedo shell-command --patterns="*.py" --recursive --command='kill -HUP `cat /tmp/gunicorn.pid`' /path/to/project/
复制代码

转载请保留如下信息:

原文连接: www.vimiix.com/post/2018/0…

相关文章
相关标签/搜索