优雅地停止Waitress Web服务器

时间:2015-09-17 01:41:20

标签: pyramid waitress

我在后台线程中启动Waitress Web服务器以运行功能测试。如何以干净(ish)方式在测试结束时清理和退出女服务员?公共女服务员API仅提供单向入口点,期望KeyboardInterrupt作为退出信号。

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

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

"""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()

1 个答案:

答案 0 :(得分:2)

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

退房:http://webtest.readthedocs.org/en/latest/http.html

根据文档,它专门用于casperjs或selenium。