Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

An ability to access PubSubHub from outside Flet app #3446

Merged
merged 3 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 3 additions & 10 deletions sdk/python/packages/flet/src/flet/fastapi/flet_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@
DEFAULT_FLET_SESSION_TIMEOUT = 3600
DEFAULT_FLET_OAUTH_STATE_TIMEOUT = 600

_pubsubhubs_lock = asyncio.Lock()
_pubsubhubs = {}


class FletApp(LocalConnection):
def __init__(
Expand Down Expand Up @@ -98,13 +95,9 @@ async def handle(self, websocket: WebSocket):
else ""
)

async with _pubsubhubs_lock:
psh = _pubsubhubs.get(self.__session_handler, None)
if psh is None:
psh = PubSubHub(loop=self.__loop, executor=app_manager.executor)
_pubsubhubs[self.__session_handler] = psh
self.pubsubhub = psh

self.pubsubhub = app_manager.get_pubsubhub(
self.__session_handler, loop=self.__loop
)
self.page_url = str(websocket.url).rsplit("/", 1)[0]
self.page_name = websocket.url.path.rsplit("/", 1)[0].lstrip("/")

Expand Down
16 changes: 16 additions & 0 deletions sdk/python/packages/flet/src/flet/fastapi/flet_app_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from flet_core.connection import Connection
from flet_core.locks import NopeLock
from flet_core.page import Page
from flet_core.pubsub.pubsub_hub import PubSubHub
from flet_core.utils.concurrency_utils import is_pyodide

logger = logging.getLogger(flet_fastapi.__name__)
Expand All @@ -31,11 +32,26 @@ def __init__(self):
self.__evict_oauth_states_task = None
self.__temp_dirs = {}
self.__executor = ThreadPoolExecutor(thread_name_prefix="flet_fastapi")
self.__pubsubhubs_lock = threading.Lock()
self.__pubsubhubs = {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider using an asyncio.Lock instead of threading.Lock

Since the rest of the code appears to be using asyncio constructs, it might be more consistent and potentially safer to use an asyncio.Lock instead of threading.Lock.

Suggested change
self.__pubsubhubs_lock = threading.Lock()
self.__pubsubhubs = {}
self.__pubsubhubs_lock = asyncio.Lock()
self.__pubsubhubs = {}


@property
def executor(self):
return self.__executor

def get_pubsubhub(
self, session_handler, loop: Optional[asyncio.AbstractEventLoop] = None
):
Comment on lines +42 to +44
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Add type hint for session_handler parameter

To improve code readability and maintainability, consider adding a type hint for the session_handler parameter.

Suggested change
def get_pubsubhub(
self, session_handler, loop: Optional[asyncio.AbstractEventLoop] = None
):
def get_pubsubhub(
self, session_handler: SessionHandlerType, loop: Optional[asyncio.AbstractEventLoop] = None
):

with self.__pubsubhubs_lock:
psh = self.__pubsubhubs.get(session_handler, None)
if psh is None:
Comment on lines +46 to +47
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Potential race condition with pubsubhubs dictionary

Although the lock should prevent race conditions, consider using a defaultdict to simplify the logic and reduce the risk of potential issues.

psh = PubSubHub(
loop=loop if loop else asyncio.get_running_loop(),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Replace if-expression with or (or-if-exp-identity)

Suggested change
loop=loop if loop else asyncio.get_running_loop(),
loop=loop or asyncio.get_running_loop(),


ExplanationHere we find ourselves setting a value if it evaluates to True, and otherwise
using a default.

The 'After' case is a bit easier to read and avoids the duplication of
input_currency.

It works because the left-hand side is evaluated first. If it evaluates to
true then currency will be set to this and the right-hand side will not be
evaluated. If it evaluates to false the right-hand side will be evaluated and
currency will be set to DEFAULT_CURRENCY.

executor=self.__executor,
)
self.__pubsubhubs[session_handler] = psh
return psh

async def start(self):
"""
Background task evicting expired app data. Must be called at FastAPI application startup.
Expand Down