瀏覽代碼

Adding the get decorator
Adding examples for add_route and ui.get in main.py

Christoph Trappe 3 年之前
父節點
當前提交
2dd415148f
共有 2 個文件被更改,包括 48 次插入2 次删除
  1. 31 0
      main.py
  2. 17 2
      nicegui/ui.py

+ 31 - 0
main.py

@@ -354,4 +354,35 @@ with example(ui.page):
 
     ui.link('Visit other page', '/other_page')
 
+add_route = """###Route
+
+Add a new route by calling `ui.add_route` with a starlette route including a path and a function to be called. 
+Routed paths must start with a '/'.
+"""
+with example(add_route):
+    import starlette
+
+    ui.add_route(
+        starlette.routing.Route(
+            '/new/route',
+            lambda request: starlette.responses.PlainTextResponse('Response')
+        )
+    )
+
+    ui.link('Try the new route!', '/new/route')
+
+get_decorator = """###Get decorator
+Syntactic sugar to add routes. Decorating a function with the @ui.get makes it available at the specified endpoint, 
+e.g. /another/route/1
+"""
+with example(get_decorator):
+    import starlette
+
+    @ui.get('/another/route/{id}')
+    def produce_plain_response(request):
+        path_param_id = request.path_params['id']
+        return starlette.responses.PlainTextResponse(f'Response {path_param_id}')
+
+    ui.link('Try yet another route!', '/another/route/1')
+
 ui.run()

+ 17 - 2
nicegui/ui.py

@@ -41,7 +41,22 @@ class Ui:
 
     def __init__(self, app) -> None:
         self.app = app
-        
+
+    def get(self, path: str):
+        """
+        Use as a decorator for a function like @ui.get('/another/route/{id}').
+        :param path: String that starts with a '/'.
+        :return:
+        """
+        def decorator(func):
+            from starlette.routing import Route
+            self.add_route(Route(path, func))
+            return func
+        return decorator
 
     def add_route(self, route):
-        self.app.routes.insert(0, route)
+        """
+        :param route: A starlette Route including a path and a function to be called.
+        :return:
+        """
+        self.app.routes.insert(0, route)