Skip to content

Commit

Permalink
PubSub sync and some async page functions removed
Browse files Browse the repository at this point in the history
  • Loading branch information
FeodorFitsner committed Feb 23, 2024
1 parent 759103b commit 5103072
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 179 deletions.
8 changes: 5 additions & 3 deletions sdk/python/packages/flet-core/src/flet_core/event_handler.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from flet_core.utils import is_asyncio, is_coroutine
import asyncio

from flet_core.utils import is_asyncio


class EventHandler:
Expand Down Expand Up @@ -39,12 +41,12 @@ async def __async_handler(self, e):
r.data = e.data
r.control = e.control
r.page = e.page
if is_coroutine(h):
if asyncio.iscoroutinefunction(h):
await h(r)
else:
h(r)
else:
if is_coroutine(h):
if asyncio.iscoroutinefunction(h):
await h(e)
else:
h(e)
Expand Down
100 changes: 26 additions & 74 deletions sdk/python/packages/flet-core/src/flet_core/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Tuple, Union, cast
from urllib.parse import urlparse
from warnings import warn

import flet_core
from flet_core.adaptive_control import AdaptiveControl
Expand Down Expand Up @@ -49,7 +50,8 @@
ThemeMode,
ThemeModeString,
)
from flet_core.utils import is_asyncio, is_coroutine
from flet_core.utils import is_asyncio
from flet_core.utils.concurrency_utils import is_pyodide
from flet_core.view import View

logger = logging.getLogger(flet_core.__name__)
Expand Down Expand Up @@ -124,7 +126,7 @@ def __init__(
self.__pool = pool
self._index = {self._Control__uid: self} # index with all page controls

self.__lock = threading.Lock() if not is_asyncio() else NopeLock()
self.__lock = threading.Lock() if not is_pyodide() else NopeLock()
self.__async_lock = asyncio.Lock() if is_asyncio() else AsyncNopeLock()

self.__views = [View()]
Expand Down Expand Up @@ -289,12 +291,8 @@ def update(self, *controls):
self.__handle_mount_unmount(*r)

async def update_async(self, *controls):
async with self.__async_lock:
if len(controls) == 0:
r = await self.__update_async(self)
else:
r = await self.__update_async(*controls)
await self.__handle_mount_unmount_async(*r)
warn("Obsolete. Use page.update() method instead.")
self.update(*controls)

def add(self, *controls):
with self.__lock:
Expand All @@ -303,10 +301,8 @@ def add(self, *controls):
self.__handle_mount_unmount(*r)

async def add_async(self, *controls):
async with self.__async_lock:
self._controls.extend(controls)
r = await self.__update_async(self)
await self.__handle_mount_unmount_async(*r)
warn("Obsolete. Use page.add() method instead.")
self.add(*controls)

def insert(self, at, *controls):
with self.__lock:
Expand All @@ -318,13 +314,8 @@ def insert(self, at, *controls):
self.__handle_mount_unmount(*r)

async def insert_async(self, at, *controls):
async with self.__async_lock:
n = at
for control in controls:
self._controls.insert(n, control)
n += 1
r = await self.__update_async(self)
await self.__handle_mount_unmount_async(*r)
warn("Obsolete. Use page.insert() method instead.")
self.insert(at, *controls)

def remove(self, *controls):
with self.__lock:
Expand All @@ -334,11 +325,8 @@ def remove(self, *controls):
self.__handle_mount_unmount(*r)

async def remove_async(self, *controls):
async with self.__async_lock:
for control in controls:
self._controls.remove(control)
r = await self.__update_async(self)
await self.__handle_mount_unmount_async(*r)
warn("Obsolete. Use page.remove() method instead.")
self.remove(*controls)

def remove_at(self, index):
with self.__lock:
Expand All @@ -347,18 +335,16 @@ def remove_at(self, index):
self.__handle_mount_unmount(*r)

async def remove_at_async(self, index):
async with self.__async_lock:
self._controls.pop(index)
r = await self.__update_async(self)
await self.__handle_mount_unmount_async(*r)
warn("Obsolete. Use page.remove_at() method instead.")
self.remove_at(index)

def clean(self):
self._clean(self)
self._controls.clear()

async def clean_async(self):
await self._clean_async(self)
self._controls.clear()
warn("Obsolete. Use page.clean() method instead.")
self.clean()

def _clean(self, control: Control):
with self.__lock:
Expand All @@ -373,19 +359,6 @@ def _clean(self, control: Control):
for c in removed_controls:
c.will_unmount()

async def _clean_async(self, control: Control):
async with self.__async_lock:
control._previous_children.clear()
assert control.uid is not None
removed_controls = []
for child in control._get_children():
removed_controls.extend(
self._remove_control_recursively(self.index, child)
)
await self._send_command_async("clean", [control.uid])
for c in removed_controls:
await c.will_unmount_async()

def _close(self):
self.__pubsub.unsubscribe_all()
removed_controls = self._remove_control_recursively(self.index, self)
Expand All @@ -395,12 +368,8 @@ def _close(self):
self.__close_internal()

async def _close_async(self):
await self.__pubsub.unsubscribe_all_async()
removed_controls = self._remove_control_recursively(self.index, self)
for c in removed_controls:
await c.will_unmount_async()
c._dispose()
self.__close_internal()
warn("Obsolete. Use page.clean() method instead.")
self.clean()

def __close_internal(self):
self._controls.clear()
Expand All @@ -421,17 +390,6 @@ def __update(self, *controls) -> Tuple[List[Control], List[Control]]:
self.__update_control_ids(added_controls, results)
return added_controls, removed_controls

async def __update_async(self, *controls) -> Tuple[List[Control], List[Control]]:
if self.__conn is None:
raise PageDisconnectedException("Page has been disconnected")
commands, added_controls, removed_controls = self.__prepare_update(*controls)
self.__validate_controls_page(added_controls)
results = (
await self.__conn.send_commands_async(self._session_id, commands)
).results
self.__update_control_ids(added_controls, results)
return added_controls, removed_controls

def __prepare_update(self, *controls):
added_controls = []
removed_controls = []
Expand Down Expand Up @@ -474,20 +432,13 @@ def __handle_mount_unmount(self, added_controls, removed_controls):
for ctrl in added_controls:
ctrl.did_mount()

async def __handle_mount_unmount_async(self, added_controls, removed_controls):
for ctrl in removed_controls:
await ctrl.will_unmount_async()
ctrl.page = None
for ctrl in added_controls:
await ctrl.did_mount_async()

def error(self, message=""):
with self.__lock:
self._send_command("error", [message])

async def error_async(self, message=""):
async with self.__async_lock:
await self._send_command_async("error", [message])
warn("Obsolete. Use page.error() method instead.")
self.error(message)

async def on_event_async(self, e: Event):
logger.debug(f"page.on_event_async: {e.target} {e.name} {e.data}")
Expand All @@ -500,13 +451,14 @@ async def on_event_async(self, e: Event):
ce = ControlEvent(e.target, e.name, e.data, self._index[e.target], self)
handler = self._index[e.target].event_handlers.get(e.name)
if handler:
if is_coroutine(handler):
if asyncio.iscoroutinefunction(handler):
await handler(ce)
elif is_pyodide():
handler(ce)
else:
# TODO - handle pyodide mode
# run in thread pool
await asyncio.get_running_loop().run_in_executor(
self.__pool, handler, ce
self.__loop.call_soon_threadsafe(
self.__loop.run_in_executor, self.__pool, handler, ce
)

def __on_page_change_event(self, data):
Expand Down Expand Up @@ -1167,7 +1119,7 @@ def auth(self):

# pubsub
@property
def pubsub(self):
def pubsub(self) -> PubSub:
return self.__pubsub

# overlay
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flet_core.utils.concurrency_utils import is_asyncio, is_coroutine
from flet_core.utils.concurrency_utils import is_asyncio, is_pyodide
from flet_core.utils.slugify import slugify
from flet_core.utils.strings import random_string
from flet_core.utils.vector import Vector
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import asyncio
import inspect
import sys


Expand All @@ -10,5 +9,5 @@ def is_asyncio():
return False


def is_coroutine(method):
return inspect.iscoroutinefunction(method)
def is_pyodide():
return sys.platform == "emscripten"
3 changes: 1 addition & 2 deletions sdk/python/packages/flet-pyodide/src/flet/flet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from flet.pyodide_connection import PyodideConnection
from flet_core.event import Event
from flet_core.page import Page
from flet_core.utils import is_coroutine

logger = logging.getLogger(flet.__name__)

Expand Down Expand Up @@ -66,7 +65,7 @@ async def on_session_created(session_data):
logger.info(f"Session started: {session_data.sessionID}")
try:
assert target is not None
if is_coroutine(target):
if asyncio.iscoroutinefunction(target):
await target(page)
else:
target(page)
Expand Down
4 changes: 2 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 @@ -16,7 +16,7 @@
from flet_core.event import Event
from flet_core.page import Page
from flet_core.types import AppView, WebRenderer
from flet_core.utils import is_coroutine, random_string
from flet_core.utils import random_string
from flet_runtime.flet_socket_server import FletSocketServer
from flet_runtime.utils import (
get_arch,
Expand Down Expand Up @@ -233,7 +233,7 @@ async def on_session_created(session_data):
logger.info(f"Session started: {session_data.sessionID}")
try:
assert session_handler is not None
if is_coroutine(session_handler):
if asyncio.iscoroutinefunction(session_handler):
await session_handler(page)
else:
# run in thread pool
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
RegisterWebClientRequestPayload,
)
from flet_core.utils import random_string
from flet_runtime.pubsub import PubSubHub
from flet_runtime.utils import get_free_tcp_port, is_windows

logger = logging.getLogger(flet_runtime.__name__)
Expand All @@ -43,6 +44,7 @@ def __init__(
self.__on_session_created = on_session_created
self.__blocking = blocking
self.__pool = pool
self.pubsubhub = PubSubHub(loop=asyncio.get_running_loop(), pool=pool)
self.__running_tasks = set()

async def start(self):
Expand Down
Loading

0 comments on commit 5103072

Please sign in to comment.