Browse Source

Merge pull request #1238 from BrianLandry/disable

Added disable context manager demo
Falko Schindler 1 year ago
parent
commit
eb716f7a07
1 changed files with 24 additions and 0 deletions
  1. 24 0
      website/more_documentation/button_documentation.py

+ 24 - 0
website/more_documentation/button_documentation.py

@@ -33,3 +33,27 @@ def more() -> None:
             ui.label('Two')
             await b.clicked()
             ui.label('Three')
+
+    @text_demo('Disable button with a context manager', '''
+        This showcases a context manager that can be used to disable a button for the duration of an async process.
+    ''')
+    def disable_context_manager() -> None:
+        from contextlib import contextmanager
+
+        import httpx
+
+        @contextmanager
+        def disable(button: ui.button) -> None:
+            button.disable()
+            try:
+                yield
+            finally:
+                button.enable()
+
+        async def get_slow_response(button: ui.button) -> None:
+            with disable(button):
+                async with httpx.AsyncClient() as client:
+                    response = await client.get('https://httpbin.org/delay/1', timeout=5)
+                    ui.notify(f'Response code: {response.status_code}')
+
+        ui.button('Get slow response', on_click=lambda e: get_slow_response(e.sender))