From e34c7ad5a75486b9ccbe9ace43b00a59371b2c9a Mon Sep 17 00:00:00 2001 From: RomanZhukov Date: Wed, 29 Jan 2025 11:53:51 +0500 Subject: [PATCH] aux server back to http --- aiohttp_devtools/runserver/config.py | 8 ++++++-- aiohttp_devtools/runserver/main.py | 7 +++---- aiohttp_devtools/runserver/serve.py | 8 ++++---- aiohttp_devtools/runserver/watch.py | 9 ++++++--- tests/test_runserver_with_ssl.py | 8 ++++---- 5 files changed, 23 insertions(+), 17 deletions(-) diff --git a/aiohttp_devtools/runserver/config.py b/aiohttp_devtools/runserver/config.py index 4ffcca50..4c58021a 100644 --- a/aiohttp_devtools/runserver/config.py +++ b/aiohttp_devtools/runserver/config.py @@ -28,6 +28,8 @@ 'create_app', ] +DEFAULT_PORT = 8000 + INFER_HOST = '' @@ -87,9 +89,11 @@ def __init__(self, *, self.bind_address = bind_address if main_port is None: - main_port = 8000 if ssl_context_factory_name is None else 8443 + main_port = DEFAULT_PORT if ssl_context_factory_name is None else DEFAULT_PORT + 443 self.main_port = main_port - self.aux_port = aux_port or (main_port + 1) + if aux_port is None: + aux_port = main_port + 1 if ssl_context_factory_name is None else DEFAULT_PORT + 1 + self.aux_port = aux_port self.browser_cache = browser_cache self.ssl_context_factory_name = ssl_context_factory_name logger.debug('config loaded:\n%s', self) diff --git a/aiohttp_devtools/runserver/main.py b/aiohttp_devtools/runserver/main.py index 746f60c2..86d2611b 100644 --- a/aiohttp_devtools/runserver/main.py +++ b/aiohttp_devtools/runserver/main.py @@ -32,8 +32,7 @@ def runserver(**config_kwargs: Any) -> RunServer: # force a full reload in sub processes so they load an updated version of code, this must be called only once set_start_method('spawn') config = Config(**config_kwargs) - module = config.import_module() - ssl_context = config.get_ssl_context(module) + config.import_module() asyncio.run(check_port_open(config.main_port, host=config.bind_address)) @@ -51,7 +50,7 @@ def runserver(**config_kwargs: Any) -> RunServer: logger.debug('starting livereload to watch %s', config.static_path_str) aux_app.cleanup_ctx.append(static_manager.cleanup_ctx) - url = '{0.protocol}://{0.host}:{0.aux_port}'.format(config) + url = 'http://{0.host}:{0.aux_port}'.format(config) logger.info('Starting aux server at %s ◆', url) if config.static_path: @@ -59,7 +58,7 @@ def runserver(**config_kwargs: Any) -> RunServer: logger.info('serving static files from ./%s/ at %s%s', rel_path, url, config.static_url) return {"app": aux_app, "host": config.bind_address, "port": config.aux_port, - "shutdown_timeout": 0.01, "access_log_class": AuxAccessLogger, "ssl_context": ssl_context} + "shutdown_timeout": 0.01, "access_log_class": AuxAccessLogger, "ssl_context": None} def serve_static(*, static_path: str, livereload: bool = True, bind_address: str = "localhost", port: int = 8000, diff --git a/aiohttp_devtools/runserver/serve.py b/aiohttp_devtools/runserver/serve.py index ec265043..4e58715b 100644 --- a/aiohttp_devtools/runserver/serve.py +++ b/aiohttp_devtools/runserver/serve.py @@ -32,7 +32,7 @@ except ImportError: static_root_key = None # type: ignore[assignment] -LIVE_RELOAD_HOST_SNIPPET = '\n\n' +LIVE_RELOAD_HOST_SNIPPET = '\n\n' LIVE_RELOAD_LOCAL_SNIPPET = b'\n\n' LAST_RELOAD = web.AppKey("LAST_RELOAD", List[float]) @@ -84,7 +84,7 @@ async def on_prepare(request: web.Request, response: web.StreamResponse) -> None or request.path.startswith("/_debugtoolbar") or "text/html" not in response.content_type): return - lr_snippet = LIVE_RELOAD_HOST_SNIPPET.format(config.protocol, get_host(request), config.aux_port) + lr_snippet = LIVE_RELOAD_HOST_SNIPPET.format(get_host(request), config.aux_port) dft_logger.debug("appending live reload snippet '%s' to body", lr_snippet) response.body += lr_snippet.encode() response.headers[CONTENT_LENGTH] = str(len(response.body)) @@ -105,7 +105,7 @@ async def no_cache_middleware(request: web.Request, handler: Handler) -> web.Str # we set the app key even in middleware to make the switch to production easier and for backwards compat. @web.middleware async def static_middleware(request: web.Request, handler: Handler) -> web.StreamResponse: - static_url = '{}://{}:{}/{}'.format(config.protocol, get_host(request), config.aux_port, static_path) + static_url = 'http://{}:{}/{}'.format(get_host(request), config.aux_port, static_path) dft_logger.debug('setting app static_root_url to "%s"', static_url) _change_static_url(request.app, static_url) return await handler(request) @@ -126,7 +126,7 @@ def shutdown() -> NoReturn: config.protocol, config.host, config.main_port, path)) if config.static_path is not None: - static_url = '{}://{}:{}/{}'.format(config.protocol, config.host, config.aux_port, static_path) + static_url = 'http://{}:{}/{}'.format(config.host, config.aux_port, static_path) dft_logger.debug('settings app static_root_url to "%s"', static_url) _set_static_url(app, static_url) diff --git a/aiohttp_devtools/runserver/watch.py b/aiohttp_devtools/runserver/watch.py index eff77b89..5adbc937 100644 --- a/aiohttp_devtools/runserver/watch.py +++ b/aiohttp_devtools/runserver/watch.py @@ -16,6 +16,7 @@ from ..logs import rs_dft_logger as logger from .config import Config from .serve import LAST_RELOAD, STATIC_PATH, WS, serve_main_app, src_reload +import ssl class WatchTask: @@ -55,7 +56,9 @@ def __init__(self, config: Config): self._reloads = 0 self._session: Optional[ClientSession] = None self._runner = None + self.ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) if config.protocol == 'https' else None assert self._config.watch_path + super().__init__(self._config.watch_path) async def _run(self, live_checks: int = 150) -> None: @@ -112,7 +115,7 @@ async def _src_reload_when_live(self, checks: int) -> None: for i in range(checks): await asyncio.sleep(0.1) try: - async with self._session.get(url): + async with self._session.get(url, ssl=self.ssl_context): pass except OSError as e: logger.debug('try %d | OSError %d app not running', i, e.errno) @@ -142,12 +145,12 @@ async def _stop_dev_server(self) -> None: if self._process.is_alive(): logger.debug('stopping server process...') if self._config.shutdown_by_url: # Workaround for signals not working on Windows - url = "http://{0.host}:{0.main_port}{0.path_prefix}/shutdown".format(self._config) + url = "{0.protocol}://{0.host}:{0.main_port}{0.path_prefix}/shutdown".format(self._config) logger.debug("Attempting to stop process via shutdown endpoint {}".format(url)) try: with suppress(ClientConnectionError): async with ClientSession() as session: - async with session.get(url): + async with session.get(url, ssl=self.ssl_context): pass except (ConnectionError, ClientError, asyncio.TimeoutError) as ex: if self._process.is_alive(): diff --git a/tests/test_runserver_with_ssl.py b/tests/test_runserver_with_ssl.py index 6baa0df0..e5c0360f 100644 --- a/tests/test_runserver_with_ssl.py +++ b/tests/test_runserver_with_ssl.py @@ -74,7 +74,7 @@ def get_ssl_context(): aux_port = args["port"] runapp_host = args["host"] assert isinstance(aux_app, aiohttp.web.Application) - assert aux_port == 8444 + assert aux_port == 8001 assert runapp_host == "0.0.0.0" for startup in aux_app.on_startup: loop.run_until_complete(startup(aux_app)) @@ -89,7 +89,7 @@ async def check_callback(session, sslcontext): text = await r.text() print(text) assert '

hello world

' in text - assert '' in text + assert '' in text async with session.get('https://localhost:8443/error', ssl=sslcontext) as r: assert r.status == 500 @@ -102,8 +102,8 @@ async def check_callback(session, sslcontext): loop.run_until_complete(shutdown(aux_app)) loop.run_until_complete(aux_app.cleanup()) assert ( - 'adev.server.dft INFO: Starting aux server at https://localhost:8444 ◆\n' - 'adev.server.dft INFO: serving static files from ./static_dir/ at https://localhost:8444/static/\n' + 'adev.server.dft INFO: Starting aux server at http://localhost:8001 ◆\n' + 'adev.server.dft INFO: serving static files from ./static_dir/ at http://localhost:8001/static/\n' 'adev.server.dft INFO: Starting dev server at https://localhost:8443 ●\n' ) in smart_caplog loop.run_until_complete(asyncio.sleep(.25)) # TODO(aiohttp 4): Remove this hack