Skip to content

Commit 4ca4659

Browse files
committed
add --default-file option to pyscript run
1 parent 3dfba42 commit 4ca4659

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/pyscript/plugins/run.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
def get_folder_based_http_request_handler(
1616
folder: Path,
17+
default_file: Path = None,
1718
) -> type[SimpleHTTPRequestHandler]:
1819
"""
1920
Returns a FolderBasedHTTPRequestHandler with the specified directory.
@@ -36,6 +37,16 @@ def end_headers(self):
3637
self.send_header("Cross-Origin-Resource-Policy", "cross-origin")
3738
self.send_header("Cache-Control", "no-cache, must-revalidate")
3839
SimpleHTTPRequestHandler.end_headers(self)
40+
41+
def do_GET(self):
42+
# intercept accesses to nonexistent files; replace them with the default file
43+
# this is to service SPA use cases (see Github Issue #132)
44+
if default_file:
45+
path = Path(self.translate_path(self.path))
46+
if not path.exists():
47+
self.path = f'/{default_file}'
48+
49+
return super().do_GET()
3950

4051
return FolderBasedHTTPRequestHandler
4152

@@ -58,7 +69,7 @@ def split_path_and_filename(path: Path) -> tuple[Path, str]:
5869
return abs_path, ""
5970

6071

61-
def start_server(path: Path, show: bool, port: int):
72+
def start_server(path: Path, show: bool, port: int, default_file: Path = None):
6273
"""
6374
Creates a local server to run the app on the path and port specified.
6475
@@ -76,7 +87,7 @@ def start_server(path: Path, show: bool, port: int):
7687
socketserver.TCPServer.allow_reuse_address = True
7788

7889
app_folder, filename = split_path_and_filename(path)
79-
CustomHTTPRequestHandler = get_folder_based_http_request_handler(app_folder)
90+
CustomHTTPRequestHandler = get_folder_based_http_request_handler(app_folder, default_file=default_file)
8091

8192
# Start the server within a context manager to make sure we clean up after
8293
with socketserver.TCPServer(("", port), CustomHTTPRequestHandler) as httpd:
@@ -110,6 +121,7 @@ def run(
110121
),
111122
view: bool = typer.Option(True, help="Open the app in web browser."),
112123
port: int = typer.Option(8000, help="The port that the app will run on."),
124+
default_file: Path = typer.Option(None, help="A default file to serve when a nonexistent file is accessed."),
113125
):
114126
"""
115127
Creates a local server to run the app on the path and port specified.
@@ -120,7 +132,7 @@ def run(
120132
raise cli.Abort(f"Error: Path {str(path)} does not exist.", style="red")
121133

122134
try:
123-
start_server(path, view, port)
135+
start_server(path, view, port, default_file=default_file)
124136
except OSError as e:
125137
if e.errno == 48:
126138
console.print(

0 commit comments

Comments
 (0)