1
0
Эх сурвалжийг харах

automatically convert type-annotated path arguments

Falko Schindler 3 жил өмнө
parent
commit
c2e21cfa67
2 өөрчлөгдсөн 12 нэмэгдсэн , 1 устгасан
  1. 1 0
      main.py
  2. 11 1
      nicegui/routes.py

+ 1 - 0
main.py

@@ -487,6 +487,7 @@ Syntactic sugar to add routes.
 Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
 Decorating a function with the `@ui.get` makes it available at the specified endpoint, e.g. `'/another/route/<id>'`.
 
 
 Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
 Path parameters can be passed to the request handler like with [FastAPI](https://fastapi.tiangolo.com/tutorial/path-params/).
+If type-annotated, they are automatically converted to `bool`, `int`, `float` and `complex` values.
 An optional `request` argument gives access to the complete request object.
 An optional `request` argument gives access to the complete request object.
 """
 """
 with example(get_decorator):
 with example(get_decorator):

+ 11 - 1
nicegui/routes.py

@@ -22,7 +22,17 @@ def get(self, path: str):
         @wraps(func)
         @wraps(func)
         def decorated(request: requests.Request):
         def decorated(request: requests.Request):
             args = {name: converter.convert(request.path_params.get(name)) for name, converter in converters.items()}
             args = {name: converter.convert(request.path_params.get(name)) for name, converter in converters.items()}
-            if 'request' in inspect.signature(func).parameters and 'request' not in args:
+            parameters = inspect.signature(func).parameters
+            for key in parameters:
+                if parameters[key].annotation.__name__ == 'bool':
+                    args[key] = bool(args[key])
+                if parameters[key].annotation.__name__ == 'int':
+                    args[key] = int(args[key])
+                elif parameters[key].annotation.__name__ == 'float':
+                    args[key] = float(args[key])
+                elif parameters[key].annotation.__name__ == 'complex':
+                    args[key] = complex(args[key])
+            if 'request' in parameters and 'request' not in args:
                 args['request'] = request
                 args['request'] = request
             return func(**args)
             return func(**args)
         self.add_route(routing.Route(path, decorated))
         self.add_route(routing.Route(path, decorated))