如何在指定时间内没有传入连接时关闭 CherryPy?

How to shut down CherryPy in no incoming connections for specified time?

我正在使用 CherryPy 与身份验证服务器通信。如果输入的所有信息都没有问题,脚本 运行 就可以了。但是,如果他们在输入 ID 时出错,内部 HTTP 错误屏幕会正常触发,但服务器会保持 运行ning 并且脚本中的任何其他内容都不会 运行,直到 CherryPy 引擎关闭,所以我必须手动杀死脚本。是否有一些代码可以按照

放在索引中
if timer >10 and connections == 0:
    close cherrypy (< I have a method for this already)

我主要是一个数据处理者,所以不习惯网络服务器。谷歌搜索显示当连接太多时关闭 CherryPy 的命中丢失,但在指定(短)时间内没有连接时则不会。我意识到 Web 服务器的要点通常是等待连接,所以这可能是一个奇怪的情况。尽管如此,欢迎任何帮助。

有趣的用例,您可以使用 CherryPy 插件基础设施来做类似的事情,看看这个 ActivityMonitor 插件实现,如果没有处理任何东西并且没有看到任何东西,它会关闭服务器在指定的时间内请求(在本例中为 10 秒)。

也许您需要调整 how 的逻辑以将其关闭或在 _verify 方法中执行任何其他操作。

如果您想了解更多关于 publish/subscribe 架构的信息,请查看 CherryPy Docs

import time
import threading

import cherrypy
from cherrypy.process.plugins import Monitor


class ActivityMonitor(Monitor):

    def __init__(self, bus, wait_time, monitor_time=None):
        """
        bus: cherrypy.engine
        wait_time: Seconds since last request that we consider to be active.
        monitor_time: Seconds that we'll wait before verifying the activity.
                      If is not defined, wait half the `wait_time`.
        """
        if monitor_time is None:
            # if monitor time is not defined, then verify half
            # the wait time since the last request
            monitor_time  = wait_time / 2
        super().__init__(
            bus, self._verify, monitor_time, self.__class__.__name__
        )
        # use a lock to make sure the thread that triggers the before_request
        # and after_request does not collide with the monitor method (_verify)
        self._active_request_lock = threading.Lock()
        self._active_requests = 0
        self._wait_time = wait_time
        self._last_request_ts = time.time()

    def _verify(self):
        # verify that we don't have any active requests and
        # shutdown the server in case we haven't seen any activity
        # since self._last_request_ts + self._wait_time
        with self._active_request_lock:
            if (not self._active_requests and
                self._last_request_ts + self._wait_time < time.time()):
                self.bus.exit() # shutdown the engine

    def before_request(self):
        with self._active_request_lock:
            self._active_requests += 1

    def after_request(self):
        with self._active_request_lock:
            self._active_requests -= 1
        # update the last time a request was served
        self._last_request_ts = time.time()


class Root:

    @cherrypy.expose
    def index(self):
        return "Hello user: current time {:.0f}".format(time.time())


def main():
    # here is how to use the plugin:
    ActivityMonitor(cherrypy.engine, wait_time=10, monitor_time=5).subscribe()
    cherrypy.quickstart(Root())


if __name__ == '__main__':
    main()