浏览代码

introduce add_static_files

Falko Schindler 3 年之前
父节点
当前提交
a45274ebbd
共有 2 个文件被更改,包括 12 次插入2 次删除
  1. 11 1
      nicegui/routes.py
  2. 1 1
      nicegui/ui.py

+ 11 - 1
nicegui/routes.py

@@ -2,12 +2,14 @@ import inspect
 from functools import wraps
 
 from starlette import requests, routing
+from starlette.routing import BaseRoute, Mount
+from starlette.staticfiles import StaticFiles
 
 from . import globals
 from .helpers import is_coroutine
 
 
-def add_route(self, route):
+def add_route(self, route: BaseRoute) -> None:
     """
     :param route: starlette route including a path and a function to be called
     :return:
@@ -15,6 +17,14 @@ def add_route(self, route):
     globals.app.routes.insert(0, route)
 
 
+def add_static_files(self, path: str, directory: str) -> None:
+    """
+    :param path: string that starts with a '/'
+    :param directory: folder with static files to serve under the given path
+    """
+    add_route(None, Mount(path, app=StaticFiles(directory=directory)))
+
+
 def get(self, path: str):
     """
     Use as a decorator for a function like @ui.get('/another/route/{id}').

+ 1 - 1
nicegui/ui.py

@@ -47,5 +47,5 @@ class Ui:
     from .elements.tree import Tree as tree
     from .elements.upload import Upload as upload
     from .lifecycle import on_shutdown, on_startup, shutdown_tasks, startup_tasks
-    from .routes import add_route, get
+    from .routes import add_route, add_static_files, get
     from .timer import Timer as timer