|
1 | | -import contextlib |
2 | 1 | import logging |
3 | 2 |
|
4 | 3 | from ._body import RequestContent |
|
9 | 8 | from ._network import NetworkBackend, sleep |
10 | 9 |
|
11 | 10 | __all__ = [ |
12 | | - "serve_http", "run" |
| 11 | + "Server" |
13 | 12 | ] |
14 | 13 |
|
15 | 14 | logger = logging.getLogger("httpx.server") |
@@ -84,34 +83,32 @@ async def _send_body(self, response: Response): |
84 | 83 | await self._parser.send_body(b'') |
85 | 84 |
|
86 | 85 |
|
87 | | -class HTTPServer: |
88 | | - def __init__(self, host, port): |
89 | | - self.url = f"http://{host}:{port}/" |
| 86 | +class Server: |
| 87 | + def __init__(self, app): |
| 88 | + self.app = app |
| 89 | + self.backend = NetworkBackend() |
| 90 | + self.url = 'http://127.0.0.1:8080/' |
90 | 91 |
|
91 | | - async def wait(self): |
92 | | - while(True): |
93 | | - await sleep(1) |
| 92 | + logging.basicConfig( |
| 93 | + format="%(levelname)s [%(asctime)s] %(name)s - %(message)s", |
| 94 | + datefmt="%Y-%m-%d %H:%M:%S", |
| 95 | + level=logging.DEBUG |
| 96 | + ) |
94 | 97 |
|
| 98 | + async def __aenter__(self): |
| 99 | + self._tcp_server = await self.backend.serve("127.0.0.1", 8080, self.handle_stream) |
| 100 | + await self._tcp_server.__aenter__() |
| 101 | + logger.info(f"Serving on http://127.0.0.1:8080 (Press CTRL+C to quit)") |
| 102 | + return self |
95 | 103 |
|
96 | | -@contextlib.asynccontextmanager |
97 | | -async def serve_http(endpoint): |
98 | | - async def handler(stream): |
99 | | - connection = HTTPConnection(stream, endpoint) |
100 | | - await connection.handle_requests() |
101 | | - |
102 | | - logging.basicConfig( |
103 | | - format="%(levelname)s [%(asctime)s] %(name)s - %(message)s", |
104 | | - datefmt="%Y-%m-%d %H:%M:%S", |
105 | | - level=logging.DEBUG |
106 | | - ) |
107 | | - |
108 | | - backend = NetworkBackend() |
109 | | - async with await backend.serve("127.0.0.1", 8080, handler) as server: |
110 | | - server = HTTPServer(server.host, server.port) |
111 | | - logger.info(f"Serving on {server.url} (Press CTRL+C to quit)") |
112 | | - yield server |
| 104 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 105 | + await self._tcp_server.__aexit__(exc_type, exc_val, exc_tb) |
113 | 106 |
|
| 107 | + async def handle_stream(self, stream): |
| 108 | + connection = HTTPConnection(stream, self.app) |
| 109 | + await connection.handle_requests() |
114 | 110 |
|
115 | | -async def run(app): |
116 | | - async with await serve_http(app) as server: |
117 | | - server.wait() |
| 111 | + async def serve(self): |
| 112 | + async with self as server: |
| 113 | + while(True): |
| 114 | + await sleep(1) |
0 commit comments