Skip to content

Commit

Permalink
Merge pull request #313 from lona-web-org/fscherf/linting-and-testing…
Browse files Browse the repository at this point in the history
…-fixes

linting and testing fixes
  • Loading branch information
fscherf authored Jan 8, 2023
2 parents 4844e71 + e84ff8f commit 9f58095
Show file tree
Hide file tree
Showing 17 changed files with 550 additions and 389 deletions.
17 changes: 17 additions & 0 deletions doc/content/end-user-documentation/settings.rst
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,20 @@ Server
`aiohttp documentation <https://docs.aiohttp.org/en/stable/web_reference.html#aiohttp.web.Application>`_
for details.
The default value is set to the aiohttp default of ``1024**2`` Bytes.


Feature Flags
-------------

.. setting::
:name: STOP_DAEMON_WHEN_VIEW_FINISHES
:path: lona.default_settings.STOP_DAEMON_WHEN_VIEW_FINISHES

.. note::

Added in 1.11

Default for ``LonaView.STOP_DAEMON_WHEN_VIEW_FINISHES``.

See `LonaView.is_daemon </end-user-documentation/views.html#lonaview-is-daemon>`_
for details.
3 changes: 3 additions & 0 deletions lona/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,3 +464,6 @@ def run(
args=server_args,
server=self.server,
)


LonaApp = App # TODO: remove in 2.0
4 changes: 2 additions & 2 deletions lona/client/_lona/dom-updater.js
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ export class LonaDomUpdater {
// RESET
} else if(operation == protocol.OPERATION.RESET) {
node.getAttributeNames().forEach(function(name) {
if(['id', 'class', 'style'].indexOf(name) > -1) {
if(['id', 'class', 'style', 'data-lona-node-id'].indexOf(name) > -1) {
return;

};
Expand Down Expand Up @@ -504,7 +504,7 @@ export class LonaDomUpdater {
// CLEAR
} else if(operation == protocol.OPERATION.CLEAR) {
node.getAttributeNames().forEach(function(name) {
if(['id', 'class', 'style'].indexOf(name) > -1) {
if(['id', 'class', 'style', 'data-lona-node-id'].indexOf(name) > -1) {
return;

};
Expand Down
3 changes: 3 additions & 0 deletions lona/default_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,6 @@

# server
AIOHTTP_CLIENT_MAX_SIZE = 1024**2

# feature flags
STOP_DAEMON_WHEN_VIEW_FINISHES = True # TODO: remove in 2.0
4 changes: 1 addition & 3 deletions lona/html/widget_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def extend(self, items):

def index(self, *args, **kwargs):
with self._widget.lock:
return self._original_data.count(*args, **kwargs)
return self._original_data.index(*args, **kwargs)

def insert(self, index, item):
check_value(item)
Expand Down Expand Up @@ -368,8 +368,6 @@ def __bool__(self, *args, **kwargs):


class WidgetData:
_LONA_CLASS_NAME = 'WidgetData'

def __init__(self, widget):
self._widget = widget

Expand Down
47 changes: 26 additions & 21 deletions lona/server.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import overload, Callable, TypeVar, cast, Any
from typing import overload, Callable, TypeVar, List, Dict, cast, Any
from concurrent.futures import Future
from collections.abc import Awaitable
from functools import reduce
Expand Down Expand Up @@ -29,6 +29,7 @@
from lona.response_parser import ResponseParser
from lona.templating import TemplatingEngine
from lona.imports import acquire as _acquire
from lona.worker_pool import WorkerPool
from lona.view_loader import ViewLoader
from lona.routing import Router, Route
from lona.connection import Connection
Expand All @@ -51,16 +52,17 @@


class Server:
def __init__(self, project_root, settings_paths=None,
settings_pre_overrides=None, settings_post_overrides=None,
routes=None):
def __init__(self, project_root: str,
settings_paths: List[str] | None = None,
settings_pre_overrides: Dict[str, Any] | None = None,
settings_post_overrides: Dict[str, Any] | None = None,
routes: List[Route] | None = None):

self._project_root = os.path.abspath(project_root)

self._websocket_connections = []
self._loop = None
self._worker_pool = None
self._app: Application = None
self._websocket_connections: List[Connection] = []
self._loop: asyncio.AbstractEventLoop | None = None
self._worker_pool: WorkerPool | None = None

# setup settings
server_logger.debug('setup settings')
Expand Down Expand Up @@ -189,11 +191,17 @@ def project_root(self):
return self._project_root

@property
def loop(self):
def loop(self) -> asyncio.AbstractEventLoop:
if self._loop is None:
raise RuntimeError('loop is not set')

return self._loop

@property
def worker_pool(self):
def worker_pool(self) -> WorkerPool:
if self._worker_pool is None:
raise RuntimeError('worker_pool is not set')

return self._worker_pool

@property
Expand Down Expand Up @@ -529,7 +537,7 @@ def run_coroutine_sync(
wait: None | bool = True,
) -> Future[T] | T:

future = asyncio.run_coroutine_threadsafe(coroutine, loop=self._loop)
future = asyncio.run_coroutine_threadsafe(coroutine, loop=self.loop)

if wait:
return future.result()
Expand Down Expand Up @@ -560,8 +568,8 @@ def _function():

return cast(
Future,
self._loop.run_in_executor(
self._worker_pool.get_executor(executor_name),
self.loop.run_in_executor(
self.worker_pool.get_executor(executor_name),
_function,
),
)
Expand Down Expand Up @@ -791,10 +799,7 @@ def get_view_class(
route = cast(Route, route)
view = route.view

return cast(
type[View],
self._view_loader.load(view),
)
return self._view_loader.load(view)

def get_views(
self,
Expand Down Expand Up @@ -825,10 +830,10 @@ def get_views(
url=url,
)

views = cast(
list[View],
self._view_runtime_controller.get_views(view_class=view_class),
)
if not view_class:
return []

views = self._view_runtime_controller.get_views(view_class=view_class)

if user:
for view in views.copy():
Expand Down
83 changes: 32 additions & 51 deletions lona/view.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import TYPE_CHECKING, overload, TypeVar, Union, cast
from typing import TYPE_CHECKING, TypeVar, Union, cast
from collections.abc import Awaitable, Callable
import threading
import asyncio
Expand All @@ -11,6 +11,7 @@
from lona.html.abstract_node import AbstractNode
from lona.events.input_event import InputEvent
from lona.static_files import StaticFile
from lona.exceptions import StopReason
from lona.connection import Connection
from lona.request import Request

Expand Down Expand Up @@ -93,7 +94,7 @@ async def await_awaitable() -> T:
if not pending_future.done():
pending_future.cancel()

raise self._view_runtime.stop_reason
raise cast(StopReason, self._view_runtime.stop_reason)

return asyncio.run_coroutine_threadsafe(
await_awaitable(),
Expand Down Expand Up @@ -228,75 +229,60 @@ def _await_specific_input_event(
finally:
self._view_runtime.state = VIEW_RUNTIME_STATE.RUNNING

@overload
def await_input_event(self, *nodes: AbstractNode, html: H = None) -> InputEvent: # NOQA: LN001
...

@overload
def await_input_event(self, __nodes: list[AbstractNode], html: H = None) -> InputEvent: # NOQA: LN001
...
def await_input_event(
self,
*nodes: list[AbstractNode],
html: H = None,
) -> InputEvent:

def await_input_event(self, *nodes, html=None):
return self._await_specific_input_event(
*nodes,
event_type='event',
html=html,
)

@overload
def await_click(self, *nodes: AbstractNode, html: H = None) -> InputEvent:
...

@overload
def await_click(self, __nodes: list[AbstractNode], html: H = None) -> InputEvent: # NOQA: LN001
...
def await_click(
self,
*nodes: list[AbstractNode],
html: H = None,
) -> InputEvent:

def await_click(self, *nodes, html=None):
return self._await_specific_input_event(
*nodes,
event_type='click',
html=html,
)

@overload
def await_change(self, *nodes: AbstractNode, html: H = None) -> InputEvent:
...

@overload
def await_change(self, __nodes: list[AbstractNode], html: H = None) -> InputEvent: # NOQA: LN001
...
def await_change(
self,
*nodes: list[AbstractNode],
html: H = None,
) -> InputEvent:

def await_change(self, *nodes, html=None):
return self._await_specific_input_event(
*nodes,
event_type='change',
html=html,
)

@overload
def await_focus(self, *nodes: AbstractNode, html: H = None) -> InputEvent:
...

@overload
def await_focus(self, __nodes: list[AbstractNode], html: H = None) -> InputEvent: # NOQA: LN001
...
def await_focus(
self,
*nodes: list[AbstractNode],
html: H = None,
) -> InputEvent:

def await_focus(self, *nodes, html=None):
return self._await_specific_input_event(
*nodes,
event_type='focus',
html=html,
)

@overload
def await_blur(self, *nodes: AbstractNode, html: H = None) -> InputEvent:
...

@overload
def await_blur(self, __nodes: list[AbstractNode], html: H = None) -> InputEvent: # NOQA: LN001
...
def await_blur(
self,
*nodes: list[AbstractNode],
html: H = None,
) -> InputEvent:

def await_blur(self, *nodes, html=None):
return self._await_specific_input_event(
*nodes,
event_type='blur',
Expand All @@ -312,15 +298,7 @@ def fire_view_event(self, name: str, data: dict | None = None) -> None:
)

# runtime #################################################################
@overload
def sleep(self, delay: float) -> None:
...

@overload
def sleep(self, delay: float, result: T) -> T:
...

def sleep(self, delay: float, result: None | T = None) -> None | T:
def sleep(self, delay: float, result: T | None = None) -> T | None:
self._view_runtime.state = VIEW_RUNTIME_STATE.SLEEPING

try:
Expand Down Expand Up @@ -366,3 +344,6 @@ def on_stop(self, reason: Exception | None) -> None:

def on_cleanup(self) -> None:
pass


LonaView = View # TODO: remove in 2.0
22 changes: 12 additions & 10 deletions lona/view_runtime.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Dict, cast, Any
from typing import TYPE_CHECKING, Tuple, List, Dict, cast, Any
from collections.abc import Container, Awaitable
from concurrent.futures import CancelledError
from datetime import datetime
Expand Down Expand Up @@ -29,7 +29,9 @@
from lona.events.input_event import InputEvent
from lona.imports import get_object_repr
from lona.html.document import Document
from lona.connection import Connection
from lona.request import Request
from lona.routing import Route

# avoid import cycles
if TYPE_CHECKING: # pragma: no cover
Expand All @@ -55,8 +57,12 @@ class VIEW_RUNTIME_STATE(Enum):


class ViewRuntime:
def __init__(self, server, url, route, match_info, post_data=None,
frontend=False, start_connection=None):
def __init__(
self, server: Server, url: str, route: Route,
match_info: Dict[str, Any],
post_data: Dict[str, Any] | None = None, frontend: bool = False,
start_connection: Connection | None = None,
):

self.server: Server = server
self.url = URL(url or '')
Expand Down Expand Up @@ -95,11 +101,7 @@ def __init__(self, server, url, route, match_info, post_data=None,
)

# setup state
self.connections = {}
# contains: {
# connection: (window_id, url),
# }

self.connections: Dict[Connection, Tuple[int, URL]] = {}
self.document = Document()

self.stopped: asyncio.Future[Literal[True]] = asyncio.Future(loop=self.server.loop) # NOQA: LN001
Expand All @@ -114,7 +116,7 @@ def __init__(self, server, url, route, match_info, post_data=None,
self.started_at = None
self.stopped_at = None

self.pending_input_events = {
self.pending_input_events: Dict[str, None | List[Awaitable[InputEvent] | Container[AbstractNode] | None]] = { # NOQA: LN001
'event': None,
'click': None,
'change': None,
Expand Down Expand Up @@ -166,7 +168,7 @@ def run_error_view(
request=self.request,
)

view_kwargs = {
view_kwargs: Dict[str, Any] = {
'request': self.request,
}

Expand Down
Loading

0 comments on commit 9f58095

Please sign in to comment.