Skip to content

Commit

Permalink
async methods from connection removed
Browse files Browse the repository at this point in the history
  • Loading branch information
FeodorFitsner committed Feb 25, 2024
1 parent d7edea0 commit 77f7989
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 147 deletions.
6 changes: 0 additions & 6 deletions sdk/python/packages/flet-core/src/flet_core/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,9 @@ def __init__(self):
def send_command(self, session_id: str, command: Command):
raise NotImplementedError()

async def send_command_async(self, session_id: str, command: Command):
raise NotImplementedError()

def send_commands(self, session_id: str, commands: List[Command]):
raise NotImplementedError()

async def send_commands_async(self, session_id: str, commands: List[Command]):
raise NotImplementedError()

def _get_ws_url(self, server: str):
url = server.rstrip("/")
if server.startswith("https://"):
Expand Down
97 changes: 33 additions & 64 deletions sdk/python/packages/flet-core/src/flet_core/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ async def fetch_page_details_async(self):
"clientUserAgent",
]
values = (
await self.__conn.send_commands_async(
self.__conn.send_commands(
self._session_id,
[Command(0, "get", ["page", prop]) for prop in props],
)
Expand Down Expand Up @@ -503,12 +503,8 @@ def get_upload_url(self, file_name: str, expires: int):
return r.result

async def get_upload_url_async(self, file_name: str, expires: int):
r = await self._send_command_async(
"getUploadUrl", attrs={"file": file_name, "expires": str(expires)}
)
if r.error:
raise Exception(r.error)
return r.result
warn("Obsolete. Use page.get_upload_url() method instead.")
return self.get_upload_url(file_name, expires)

def login(
self,
Expand Down Expand Up @@ -582,7 +578,7 @@ async def login_async(
auth_attrs["completePageUrl"] = up._replace(
path=f"{self.__conn.page_name}{self.route}"
).geturl()
result = await self._send_command_async("oauthAuthorize", attrs=auth_attrs)
result = self._send_command("oauthAuthorize", attrs=auth_attrs)
if result.error != "":
raise Exception(result.error)
if on_open_authorization_url:
Expand Down Expand Up @@ -683,22 +679,6 @@ def _send_command(
),
)

async def _send_command_async(
self,
name: str,
values: Optional[List[str]] = None,
attrs: Optional[Dict[str, str]] = None,
):
return await self.__conn.send_command_async(
self._session_id,
Command(
indent=0,
name=name,
values=values if values is not None else [],
attrs=attrs or {},
),
)

def set_clipboard(self, value: str):
self.__offstage.clipboard.set_data(value)

Expand Down Expand Up @@ -876,7 +856,7 @@ async def invoke_method_async(
self.__method_calls[method_id] = evt

# call method
result = await self._send_command_async(
result = self._send_command(
"invokeMethod", values=[method_id, method_name, control_id], attrs=arguments
)

Expand Down Expand Up @@ -923,9 +903,8 @@ def show_snack_bar(self, snack_bar: SnackBar):
self.__offstage.update()

async def show_snack_bar_async(self, snack_bar: SnackBar):
self.__offstage.snack_bar = snack_bar
self.__offstage.snack_bar.open = True
await self.__offstage.update_async()
warn("Obsolete. Use page.show_snack_bar() method instead.")
self.show_snack_bar(snack_bar)

#
# Dialogs
Expand All @@ -936,19 +915,17 @@ def show_dialog(self, dialog: Union[AlertDialog, CupertinoAlertDialog]):
self.__offstage.update()

async def show_dialog_async(self, dialog: Union[AlertDialog, CupertinoAlertDialog]):
self.__offstage.dialog = dialog
self.__offstage.dialog.open = True
await self.__offstage.update_async()
warn("Obsolete. Use page.show_dialog() method instead.")
self.show_dialog(dialog)

def close_dialog(self):
if self.__offstage.dialog is not None:
self.__offstage.dialog.open = False
self.__offstage.update()

async def close_dialog_async(self):
if self.__offstage.dialog is not None:
self.__offstage.dialog.open = False
await self.__offstage.update_async()
warn("Obsolete. Use page.close_dialog() method instead.")
self.close_dialog()

#
# Banner
Expand All @@ -959,19 +936,17 @@ def show_banner(self, banner: Banner):
self.__offstage.update()

async def show_banner_async(self, banner: Banner):
self.__offstage.banner = banner
self.__offstage.banner.open = True
await self.__offstage.update_async()
warn("Obsolete. Use page.show_banner() method instead.")
self.show_banner(banner)

def close_banner(self):
if self.__offstage.banner is not None:
self.__offstage.banner.open = False
self.__offstage.update()

async def close_banner_async(self):
if self.__offstage.banner is not None:
self.__offstage.banner.open = False
await self.__offstage.update_async()
warn("Obsolete. Use page.close_banner() method instead.")
self.close_banner()

#
# BottomSheet
Expand All @@ -982,19 +957,17 @@ def show_bottom_sheet(self, bottom_sheet: BottomSheet):
self.__offstage.update()

async def show_bottom_sheet_async(self, bottom_sheet: BottomSheet):
self.__offstage.bottom_sheet = bottom_sheet
self.__offstage.bottom_sheet.open = True
await self.__offstage.update_async()
warn("Obsolete. Use page.show_bottom_sheet() method instead.")
self.show_bottom_sheet(bottom_sheet)

def close_bottom_sheet(self):
if self.__offstage.bottom_sheet is not None:
self.__offstage.bottom_sheet.open = False
self.__offstage.update()

async def close_bottom_sheet_async(self):
if self.__offstage.bottom_sheet is not None:
self.__offstage.bottom_sheet.open = False
await self.__offstage.update_async()
warn("Obsolete. Use page.close_bottom_sheet() method instead.")
self.close_bottom_sheet()

# Drawer
#
Expand All @@ -1004,19 +977,17 @@ def show_drawer(self, drawer: NavigationDrawer):
self.update()

async def show_drawer_async(self, drawer: NavigationDrawer):
self.drawer = drawer
self.drawer.open = True
await self.update_async()
warn("Obsolete. Use page.show_drawer() method instead.")
self.show_drawer(drawer)

def close_drawer(self):
if self.drawer is not None:
self.drawer.open = False
self.update()

async def close_drawer_async(self):
if self.drawer is not None:
self.drawer.open = False
await self.drawer.update_async()
warn("Obsolete. Use page.close_drawer() method instead.")
self.close_drawer()

# End_drawer
#
Expand All @@ -1026,43 +997,41 @@ def show_end_drawer(self, end_drawer: NavigationDrawer):
self.update()

async def show_end_drawer_async(self, end_drawer: NavigationDrawer):
self.end_drawer = end_drawer
self.end_drawer.open = True
await self.update_async()
warn("Obsolete. Use page.show_end_drawer() method instead.")
self.show_end_drawer(end_drawer)

def close_end_drawer(self):
if self.end_drawer is not None:
self.end_drawer.open = False
self.update()

async def close_end_drawer_async(self):
if self.end_drawer is not None:
self.end_drawer.open = False
await self.end_drawer.update_async()
warn("Obsolete. Use page.close_end_drawer() method instead.")
self.close_end_drawer()

def window_destroy(self):
self._set_attr("windowDestroy", "true")
self.update()

async def window_destroy_async(self):
self._set_attr("windowDestroy", "true")
await self.update_async()
warn("Obsolete. Use page.window_destroy() method instead.")
self.window_destroy()

def window_center(self):
self._set_attr("windowCenter", str(time.time()))
self.update()

async def window_center_async(self):
self._set_attr("windowCenter", str(time.time()))
await self.update_async()
warn("Obsolete. Use page.window_center() method instead.")
self.window_center()

def window_close(self):
self._set_attr("windowClose", str(time.time()))
self.update()

async def window_close_async(self):
self._set_attr("windowClose", str(time.time()))
await self.update_async()
warn("Obsolete. Use page.window_close() method instead.")
self.window_close()

# QueryString
@property
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,12 @@ async def __on_message(self, data: str):
# it's something else
raise Exception(f'Unknown message "{msg.action}": {msg.payload}')

async def send_command_async(self, session_id: str, command: Command):
return self.send_command(session_id, command)

def send_command(self, session_id: str, command: Command):
result, message = self._process_command(command)
if message:
self.__send(message)
return PageCommandResponsePayload(result=result, error="")

async def send_commands_async(self, session_id: str, commands: List[Command]):
return self.send_commands(session_id, commands)

def send_commands(self, session_id: str, commands: List[Command]):
results = []
messages = []
Expand Down
5 changes: 3 additions & 2 deletions sdk/python/packages/flet-runtime/src/flet_runtime/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,9 @@ async def on_session_created(session_data):
)

conn = FletSocketServer(
port,
uds_path,
loop=asyncio.get_running_loop(),
port=port,
uds_path=uds_path,
on_event=on_event,
on_session_created=on_session_created,
blocking=blocking,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
class FletSocketServer(LocalConnection):
def __init__(
self,
loop: asyncio.AbstractEventLoop,
port: int = 0,
uds_path: Optional[str] = None,
on_event=None,
Expand All @@ -43,6 +44,7 @@ def __init__(
self.__on_event = on_event
self.__on_session_created = on_session_created
self.__blocking = blocking
self.__loop = loop
self.__pool = pool
self.pubsubhub = PubSubHub(loop=asyncio.get_running_loop(), pool=pool)
self.__running_tasks = set()
Expand Down Expand Up @@ -122,7 +124,7 @@ async def __on_message(self, data: str):
self._client_details = RegisterWebClientRequestPayload(**msg.payload)

# register response
await self.__send_async(self._create_register_web_client_response())
self.__send(self._create_register_web_client_response())

# start session
if self.__on_session_created is not None:
Expand All @@ -149,33 +151,12 @@ async def __on_message(self, data: str):
self.__running_tasks.add(task)
task.add_done_callback(self.__running_tasks.discard)

async def send_command_async(self, session_id: str, command: Command):
result, message = self._process_command(command)
if message:
await self.__send_async(message)
return PageCommandResponsePayload(result=result, error="")

def send_command(self, session_id: str, command: Command):
result, message = self._process_command(command)
if message:
self.__send(message)
return PageCommandResponsePayload(result=result, error="")

async def send_commands_async(self, session_id: str, commands: List[Command]):
results = []
messages = []
for command in commands:
result, message = self._process_command(command)
if command.name in ["add", "get"]:
results.append(result)
if message:
messages.append(message)
if len(messages) > 0:
await self.__send_async(
ClientMessage(ClientActions.PAGE_CONTROLS_BATCH, messages)
)
return PageCommandsBatchResponsePayload(results=results, error="")

def send_commands(self, session_id: str, commands: List[Command]):
results = []
messages = []
Expand All @@ -189,15 +170,10 @@ def send_commands(self, session_id: str, commands: List[Command]):
self.__send(ClientMessage(ClientActions.PAGE_CONTROLS_BATCH, messages))
return PageCommandsBatchResponsePayload(results=results, error="")

async def __send_async(self, message: ClientMessage):
j = json.dumps(message, cls=CommandEncoder, separators=(",", ":"))
logger.debug(f"__send_async: {j}")
await self.__send_queue.put(j)

def __send(self, message: ClientMessage):
j = json.dumps(message, cls=CommandEncoder, separators=(",", ":"))
logger.debug(f"__send: {j}")
self.__send_queue._loop.call_soon_threadsafe(self.__send_queue.put_nowait, j)
self.__loop.call_soon_threadsafe(self.__send_queue.put_nowait, j)

async def close(self):
logger.debug("Closing connection...")
Expand Down
2 changes: 2 additions & 0 deletions sdk/python/packages/flet/src/flet/fastapi/app.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import os
from typing import Awaitable, Callable, Optional, Union

Expand Down Expand Up @@ -60,6 +61,7 @@ def app(
@fastapi_app.websocket("/ws")
async def app_handler(websocket: WebSocket):
await FletApp(
asyncio.get_running_loop(),
session_handler,
session_timeout_seconds=session_timeout_seconds,
oauth_state_timeout_seconds=oauth_state_timeout_seconds,
Expand Down
Loading

0 comments on commit 77f7989

Please sign in to comment.