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

问题描述 投票:0回答:1

我正在使用CherryPy与一个认证服务器对话。 如果所有输入的信息都没有问题,脚本就能正常运行。 但是如果他们输入的ID有误,内部的HTTP错误屏幕就会启动,但是服务器一直在运行,脚本中的其他内容都不会运行,直到CherryPy引擎关闭,所以我必须手动杀死脚本。 是否有一些代码我可以放在索引中,比如说

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

我主要是一个数据管理员,所以不习惯网络服务器。Googling显示,当有太多连接时,关闭CherryPy的点击率会下降,但当指定(短时间)没有连接时,则不会。 我意识到网络服务器的作用通常是等待连接,所以这可能是一个奇怪的情况。 尽管如此,欢迎任何帮助。

python-3.x cherrypy
1个回答
2
投票

有趣的用例,你可以使用CherryPy插件infrastrcuture来做类似的事情,看看这个。ActivityMonitor 插件的实现,如果没有处理任何事情,并且在指定的时间内没有看到任何请求(在这个例子中是10秒),它就会关闭服务器。

也许你必须调整 如何 关闭它或做任何其他的事情。_verify 方法。

如果你想阅读更多关于发布订阅架构的信息,请看一下 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()
© www.soinside.com 2019 - 2024. All rights reserved.