优雅地停止 Waitress Web 服务器

Gracefully stopping Waitress web server

我正在后台线程中启动 Waitress Web 服务器以进行 运行 功能测试。如何在测试 运行 结束时以干净(ish)的方式清理并退出女服务员? public 女服务员 API 只给出一种入口点,期望 KeyboardInterrupt 作为退出信号。

目前我只是 运行 守护线程中的服务器,所有新的 Web 服务器都在等待清理,直到测试 运行ner 退出。

我的测试网络服务器代码:

"""py.test fixtures for spinning up a WSGI server for functional test run."""

import threading
import time
from pyramid.router import Router
from waitress import serve
from urllib.parse import urlparse

import pytest

from backports import typing

#: The URL where WSGI server is run from where Selenium browser loads the pages
HOST_BASE = "http://localhost:8521"


class ServerThread(threading.Thread):
    """Run WSGI server on a background thread.

    This thread starts a web server for a given WSGI application. Then the Selenium WebDriver can connect to this web server, like to any web server, for running functional tests.
    """

    def __init__(self, app:Router, hostbase:str=HOST_BASE):
        threading.Thread.__init__(self)
        self.app = app
        self.srv = None
        self.daemon = True
        self.hostbase = hostbase

    def run(self):
        """Start WSGI server on a background to listen to incoming."""
        parts = urlparse(self.hostbase)
        domain, port = parts.netloc.split(":")

        try:
            # TODO: replace this with create_server call, so we can quit this later
            serve(self.app, host='127.0.0.1', port=int(port))
        except Exception as e:
            # We are a background thread so we have problems to interrupt tests in the case of error. Try spit out something to the console.
            import traceback
            traceback.print_exc()

    def quit(self):
        """Stop test webserver."""

        # waitress has no quit

        # if self.srv:
        #    self.srv.shutdown()

Webtest 提供了一个名为 StopableWSGIServer 的 WSGI 服务器,它在一个单独的线程中启动,然后在您完成 运行 测试后可以 shutdown()

查看:https://docs.pylonsproject.org/projects/webtest/en/latest/api.html#module-webtest.http

根据文档,它是专门为与 casperjs 或 selenium 一起使用而构建的。