File: http_server.py

package info (click to toggle)
python-socks 2.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 544 kB
  • sloc: python: 5,191; sh: 8; makefile: 3
file content (51 lines) | stat: -rw-r--r-- 1,309 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import typing
import time
from multiprocessing import Process

from tests.utils import is_connectable
from tests.http_app import run_app


class HttpServerConfig(typing.NamedTuple):
    host: str
    port: int
    certfile: str = None
    keyfile: str = None

    def to_dict(self):
        d = {}
        for key, val in self._asdict().items():
            if val is not None:
                d[key] = val
        return d


class HttpServer:
    def __init__(self, config: typing.Iterable[HttpServerConfig]):
        self.config = config
        self.workers = []

    def start(self):
        for cfg in self.config:
            p = Process(target=run_app, kwargs=cfg.to_dict())
            self.workers.append(p)

        for p in self.workers:
            p.start()

    def terminate(self):
        for p in self.workers:
            p.terminate()

    def wait_until_connectable(self, host, port, timeout=10):
        count = 0
        while not is_connectable(host=host, port=port):
            if count >= timeout:
                self.terminate()
                raise Exception(
                    'The http server has not available '
                    'by (%s, %s) in %d seconds'
                    % (host, port, timeout))
            count += 1
            time.sleep(1)
        return True