|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
5 | 5 | import argparse |
| 6 | +import asyncio |
6 | 7 | import shlex |
7 | 8 | import sys |
8 | 9 | import webbrowser |
9 | | -from contextlib import asynccontextmanager |
10 | 10 | from pathlib import Path |
11 | 11 |
|
12 | 12 | import colorama |
@@ -83,40 +83,39 @@ def main(argv=()): |
83 | 83 | ignore_dirs = list(filter(None, ignore_dirs)) |
84 | 84 | ignore_handler = IgnoreFilter(ignore_dirs, args.re_ignore) |
85 | 85 |
|
86 | | - app = _create_app( |
87 | | - watch_dirs, ignore_handler, builder, serve_dir, url_host, args.open_browser |
88 | | - ) |
| 86 | + app = _create_app(watch_dirs, ignore_handler, builder, serve_dir, url_host) |
89 | 87 |
|
90 | 88 | if not args.no_initial_build: |
91 | 89 | show_message("Starting initial build") |
92 | 90 | builder(changed_paths=()) |
93 | 91 |
|
94 | 92 | show_message("Waiting to detect changes...") |
| 93 | + config = uvicorn.Config(app, host=host_name, port=port_num, log_level="warning") |
| 94 | + server = uvicorn.Server(config) |
| 95 | + |
| 96 | + async def serve(): |
| 97 | + await server.startup() |
| 98 | + if args.open_browser: |
| 99 | + webbrowser.open(f"http://{url_host}") |
| 100 | + await server.main_loop() |
| 101 | + await server.shutdown() |
| 102 | + |
95 | 103 | try: |
96 | | - uvicorn.run(app, host=host_name, port=port_num, log_level="warning") |
| 104 | + asyncio.run(serve()) |
97 | 105 | except KeyboardInterrupt: |
98 | 106 | show_message("Server ceasing operations. Cheerio!") |
99 | 107 |
|
100 | 108 |
|
101 | | -def _create_app( |
102 | | - watch_dirs, ignore_handler, builder, out_dir, url_host, open_browser=False |
103 | | -): |
| 109 | +def _create_app(watch_dirs, ignore_handler, builder, out_dir, url_host): |
104 | 110 | watcher = RebuildServer(watch_dirs, ignore_handler, change_callback=builder) |
105 | 111 |
|
106 | | - @asynccontextmanager |
107 | | - async def lifespan(app): |
108 | | - async with watcher.lifespan(app): |
109 | | - if open_browser: |
110 | | - webbrowser.open(f"http://{url_host}") |
111 | | - yield |
112 | | - |
113 | 112 | return Starlette( |
114 | 113 | routes=[ |
115 | 114 | WebSocketRoute("/websocket-reload", watcher, name="reload"), |
116 | 115 | Mount("/", app=StaticFiles(directory=out_dir, html=True), name="static"), |
117 | 116 | ], |
118 | 117 | middleware=[Middleware(JavascriptInjectorMiddleware, ws_url=url_host)], |
119 | | - lifespan=lifespan, |
| 118 | + lifespan=watcher.lifespan, |
120 | 119 | ) |
121 | 120 |
|
122 | 121 |
|
|
0 commit comments