Skip to content

Commit

Permalink
aux server back to http
Browse files Browse the repository at this point in the history
  • Loading branch information
zrvku2000 committed Jan 29, 2025
1 parent 63a268a commit e34c7ad
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 17 deletions.
8 changes: 6 additions & 2 deletions aiohttp_devtools/runserver/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
'create_app',
]

DEFAULT_PORT = 8000

INFER_HOST = '<inference>'


Expand Down Expand Up @@ -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)
Expand Down
7 changes: 3 additions & 4 deletions aiohttp_devtools/runserver/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand All @@ -51,15 +50,15 @@ 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:
rel_path = config.static_path.relative_to(os.getcwd())
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,
Expand Down
8 changes: 4 additions & 4 deletions aiohttp_devtools/runserver/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
except ImportError:
static_root_key = None # type: ignore[assignment]

LIVE_RELOAD_HOST_SNIPPET = '\n<script src="{}://{}:{}/livereload.js"></script>\n'
LIVE_RELOAD_HOST_SNIPPET = '\n<script src="http://{}:{}/livereload.js"></script>\n'
LIVE_RELOAD_LOCAL_SNIPPET = b'\n<script src="/livereload.js"></script>\n'

LAST_RELOAD = web.AppKey("LAST_RELOAD", List[float])
Expand Down Expand Up @@ -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))
Expand All @@ -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)
Expand All @@ -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)

Expand Down
9 changes: 6 additions & 3 deletions aiohttp_devtools/runserver/watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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():
Expand Down
8 changes: 4 additions & 4 deletions tests/test_runserver_with_ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -89,7 +89,7 @@ async def check_callback(session, sslcontext):
text = await r.text()
print(text)
assert '<h1>hello world</h1>' in text
assert '<script src="https://localhost:8444/livereload.js"></script>' in text
assert '<script src="http://localhost:8001/livereload.js"></script>' in text

async with session.get('https://localhost:8443/error', ssl=sslcontext) as r:
assert r.status == 500
Expand All @@ -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

0 comments on commit e34c7ad

Please sign in to comment.