code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
async def test_mixed_special_parameters(self, registry, browser_session, base_url, mock_llm):
"""Test action with multiple special injected parameters"""
from langchain_core.language_models.chat_models import BaseChatModel
@registry.action('Action with multiple special params')
async def multi_special_action(... | Test action with multiple special injected parameters | test_mixed_special_parameters | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_legacy_browser_parameter_names(self, registry, browser_session):
"""Test that legacy browser parameter names still work"""
@registry.action('Action with legacy browser param')
async def legacy_browser_action(text: str, browser: BrowserSession):
page = await browser.get_current_page()
return ... | Test that legacy browser parameter names still work | test_legacy_browser_parameter_names | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_page_parameter_optimization(self, browser_session: BrowserSession, httpserver: HTTPServer):
"""Test that actions can use page: Page parameter directly instead of browser_session"""
registry = Registry()
httpserver.expect_request('/test').respond_with_data('<html><body>Test Page</body></html>')
p... | Test that actions can use page: Page parameter directly instead of browser_session | test_page_parameter_optimization | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_action_calling_action_with_kwargs(self, registry, browser_session):
"""Test action calling another action using kwargs (current problematic pattern)"""
# Helper function that actions can call
async def helper_function(browser_session: BrowserSession, data: str):
page = await browser_session.get... | Test action calling another action using kwargs (current problematic pattern) | test_action_calling_action_with_kwargs | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_google_sheets_style_calling_pattern(self, registry, browser_session):
"""Test the specific pattern from Google Sheets actions that causes the error"""
# Simulate the _select_cell_or_range helper function
async def _select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):
page ... | Test the specific pattern from Google Sheets actions that causes the error | test_google_sheets_style_calling_pattern | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_complex_action_chain(self, registry, browser_session):
"""Test a complex chain of actions calling other actions"""
@registry.action('Base action')
async def base_action(value: str, browser_session: BrowserSession):
page = await browser_session.get_current_page()
return ActionResult(extracted... | Test a complex chain of actions calling other actions | test_complex_action_chain | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_decorated_action_rejects_positional_args(self, registry, browser_session):
"""Test that decorated actions reject positional arguments"""
@registry.action('Action that should reject positional args')
async def test_action(cell_or_range: str, browser_session: BrowserSession):
page = await browser... | Test that decorated actions reject positional arguments | test_decorated_action_rejects_positional_args | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_missing_required_browser_session(self, registry):
"""Test that actions requiring browser_session fail appropriately when not provided"""
@registry.action('Requires browser')
async def requires_browser(text: str, browser_session: BrowserSession):
page = await browser_session.get_current_page()
... | Test that actions requiring browser_session fail appropriately when not provided | test_missing_required_browser_session | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_missing_required_llm(self, registry, browser_session):
"""Test that actions requiring page_extraction_llm fail appropriately when not provided"""
from langchain_core.language_models.chat_models import BaseChatModel
@registry.action('Requires LLM')
async def requires_llm(text: str, browser_sessi... | Test that actions requiring page_extraction_llm fail appropriately when not provided | test_missing_required_llm | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_sync_action_wrapper(self, registry, browser_session):
"""Test that sync functions are properly wrapped to be async"""
@registry.action('Sync action')
def sync_action(text: str, browser_session: BrowserSession):
# This is a sync function that should be wrapped
return ActionResult(extracted_co... | Test that sync functions are properly wrapped to be async | test_sync_action_wrapper | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_excluded_actions(self, browser_session):
"""Test that excluded actions are not registered"""
registry_with_exclusions = Registry[TestContext](exclude_actions=['excluded_action'])
@registry_with_exclusions.action('Excluded action')
async def excluded_action(text: str):
return ActionResult(ext... | Test that excluded actions are not registered | test_excluded_actions | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_existing_action_models(self, registry, browser_session):
"""Test that existing action parameter models work correctly"""
@registry.action('Test search', param_model=SearchGoogleAction)
async def test_search(params: SearchGoogleAction, browser_session: BrowserSession):
return ActionResult(extrac... | Test that existing action parameter models work correctly | test_existing_action_models | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_pydantic_vs_individual_params_consistency(self, registry, browser_session):
"""Test that pydantic and individual parameter patterns produce consistent results"""
# Action using individual parameters
@registry.action('Individual params')
async def individual_params_action(text: str, number: int, ... | Test that pydantic and individual parameter patterns produce consistent results | test_pydantic_vs_individual_params_consistency | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_type1_with_param_model(self):
"""Type 1: action(params: Model, special_args...) should work"""
registry = Registry()
class ClickAction(BaseActionModel):
index: int
delay: float = 0.0
@registry.action('Click element', param_model=ClickAction)
async def click_element(params: ClickAction, browse... | Type 1: action(params: Model, special_args...) should work | test_type1_with_param_model | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_type1_with_multiple_special_params(self):
"""Type 1 with multiple special params should work"""
registry = Registry()
class ExtractAction(BaseActionModel):
goal: str
include_links: bool = False
from langchain_core.language_models.chat_models import BaseChatModel
@registry.action('Extract con... | Type 1 with multiple special params should work | test_type1_with_multiple_special_params | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_type2_with_defaults(self):
"""Type 2 with default values should preserve defaults"""
registry = Registry()
@registry.action('Scroll page')
async def scroll_page(direction: str = 'down', amount: int = 100, browser_session: BrowserSession = None):
return ActionResult(extracted_content=f'Scrolled {dir... | Type 2 with default values should preserve defaults | test_type2_with_defaults | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_type2_no_action_params(self):
"""Type 2 with only special params should work"""
registry = Registry()
@registry.action('Save PDF')
async def save_pdf(browser_session: BrowserSession, page: Page):
return ActionResult(extracted_content='Saved PDF')
action = registry.registry.actions['save_pdf']
... | Type 2 with only special params should work | test_type2_no_action_params | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_no_special_params_action(self):
"""Test action with no special params (like wait action in Controller)"""
registry = Registry()
@registry.action('Wait for x seconds default 3')
async def wait(seconds: int = 3):
await asyncio.sleep(seconds)
return ActionResult(extracted_content=f'Waited {seconds}... | Test action with no special params (like wait action in Controller) | test_no_special_params_action | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_error_on_kwargs_in_original_function(self):
"""Should error if original function has kwargs"""
registry = Registry()
with pytest.raises(ValueError, match='kwargs.*not allowed'):
@registry.action('Bad action')
async def bad_action(index: int, page: Page, **kwargs):
pass | Should error if original function has kwargs | test_error_on_kwargs_in_original_function | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_error_on_special_param_name_with_wrong_type(self):
"""Should error if special param name used with wrong type"""
registry = Registry()
# Using 'page' with str type should error
with pytest.raises(ValueError, match='conflicts with special argument.*page: Page'):
@registry.action('Navigate')
asyn... | Should error if special param name used with wrong type | test_error_on_special_param_name_with_wrong_type | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_special_params_must_match_type(self):
"""Special params with correct types should work"""
registry = Registry()
@registry.action('Good action')
async def good_action(
index: int,
page: Page, # Correct type
browser_session: BrowserSession, # Correct type
):
return ActionResult()
asse... | Special params with correct types should work | test_special_params_must_match_type | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_decorated_function_only_accepts_kwargs(self):
"""Decorated functions should only accept kwargs, no positional args"""
registry = Registry()
class MockBrowserSession:
async def get_current_page(self):
return None
@registry.action('Click')
async def click(index: int, browser_session: Bro... | Decorated functions should only accept kwargs, no positional args | test_decorated_function_only_accepts_kwargs | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_decorated_function_accepts_params_model(self):
"""Decorated function should accept params as model"""
registry = Registry()
class MockBrowserSession:
async def get_current_page(self):
return None
@registry.action('Input text')
async def input_text(index: int, text: str, browser_session... | Decorated function should accept params as model | test_decorated_function_accepts_params_model | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_decorated_function_ignores_extra_kwargs(self):
"""Decorated function should ignore extra kwargs for easy unpacking"""
registry = Registry()
class MockPage:
pass
@registry.action('Simple action')
async def simple_action(value: int, page: Page):
return ActionResult(extracted_content=str(v... | Decorated function should ignore extra kwargs for easy unpacking | test_decorated_function_ignores_extra_kwargs | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_generates_model_from_non_special_args(self):
"""Should generate param model from non-special positional args"""
registry = Registry()
@registry.action('Complex action')
async def complex_action(
query: str, max_results: int, include_images: bool = True, page: Page = None, browser_session: BrowserSe... | Should generate param model from non-special positional args | test_generates_model_from_non_special_args | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_preserves_type_annotations(self):
"""Generated model should preserve type annotations"""
registry = Registry()
@registry.action('Typed action')
async def typed_action(
count: int, rate: float, enabled: bool, name: str | None = None, browser_session: BrowserSession = None
):
return ActionResult... | Generated model should preserve type annotations | test_preserves_type_annotations | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_clear_error_for_kwargs(self):
"""Error message for kwargs should be clear"""
registry = Registry()
try:
@registry.action('Bad')
async def bad(x: int, **kwargs):
pass
pytest.fail('Should have raised ValueError')
except ValueError as e:
assert 'kwargs' in str(e).lower()
assert 'not ... | Error message for kwargs should be clear | test_clear_error_for_kwargs | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_clear_error_for_param_conflicts(self):
"""Error message for param conflicts should be helpful"""
registry = Registry()
try:
@registry.action('Bad')
async def bad(page: str):
pass
pytest.fail('Should have raised ValueError')
except ValueError as e:
error_msg = str(e)
assert 'page: ... | Error message for param conflicts should be helpful | test_clear_error_for_param_conflicts | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_mixed_param_ordering(self):
"""Should handle any ordering of action params and special params"""
registry = Registry()
from langchain_core.language_models.chat_models import BaseChatModel
# Special params mixed throughout
@registry.action('Mixed params')
async def mixed_action(
first: str,
b... | Should handle any ordering of action params and special params | test_mixed_param_ordering | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_all_params_at_end(self):
"""Should work with all action params at the end"""
registry = Registry()
@registry.action('Params at end')
async def params_at_end(page: Page, query: str, limit: int = 10):
return ActionResult()
action = registry.registry.actions['params_at_end']
assert set(action.par... | Should work with all action params at the end | test_all_params_at_end | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def test_extract_content_pattern_registration(self):
"""Test that the extract_content pattern with mixed params registers correctly"""
registry = Registry()
# This is the problematic pattern: positional arg, then special args, then kwargs with defaults
@registry.action('Extract content from page')
async def ... | Test that the extract_content pattern with mixed params registers correctly | test_extract_content_pattern_registration | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
async def test_browser_session_double_kwarg(self):
"""Run the test to diagnose browser_session parameter issue
This test demonstrates the problem and our fix. The issue happens because:
1. In controller/service.py, we have:
```python
@registry.action('Google Sheets: Select a specific cell or range of cells'... | Run the test to diagnose browser_session parameter issue
This test demonstrates the problem and our fix. The issue happens because:
1. In controller/service.py, we have:
```python
@registry.action('Google Sheets: Select a specific cell or range of cells')
async def select_cell_or_range(browser_session: Brow... | test_browser_session_double_kwarg | python | browser-use/browser-use | tests/ci/test_registry.py | https://github.com/browser-use/browser-use/blob/master/tests/ci/test_registry.py | MIT |
def walk_python_files(root: Path, ignore_dirs: Collection[str]) -> Iterator[Path]:
"""Iterate over Python files
We yield in a particular order to get the correction title section structure. Given
a directory structure of the form::
project/
__init__.py
/package
... | Iterate over Python files
We yield in a particular order to get the correction title section structure. Given
a directory structure of the form::
project/
__init__.py
/package
__init__.py
module_a.py
module_b.py
We yield the file... | walk_python_files | python | reactive-python/reactpy | docs/source/_exts/autogen_api_docs.py | https://github.com/reactive-python/reactpy/blob/master/docs/source/_exts/autogen_api_docs.py | MIT |
def attributes_to_reactjs(attributes: VdomAttributes):
"""Convert HTML attribute names to their ReactJS equivalents."""
attrs = cast(VdomAttributes, attributes.items())
attrs = cast(
VdomAttributes,
{REACT_PROP_SUBSTITUTIONS.get(k, k): v for k, v in attrs},
)
return attrs | Convert HTML attribute names to their ReactJS equivalents. | attributes_to_reactjs | python | reactive-python/reactpy | src/reactpy/transforms.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/transforms.py | MIT |
def normalize_style_attributes(self, vdom: dict[str, Any]) -> None:
"""Convert style attribute from str -> dict with camelCase keys"""
if (
"attributes" in vdom
and "style" in vdom["attributes"]
and isinstance(vdom["attributes"]["style"], str)
):
v... | Convert style attribute from str -> dict with camelCase keys | normalize_style_attributes | python | reactive-python/reactpy | src/reactpy/transforms.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/transforms.py | MIT |
def textarea_children_to_prop(vdom: VdomDict) -> None:
"""Transformation that converts the text content of a <textarea> to a ReactJS prop."""
if vdom["tagName"] == "textarea" and "children" in vdom and vdom["children"]:
text_content = vdom.pop("children")
text_content = "".join(
... | Transformation that converts the text content of a <textarea> to a ReactJS prop. | textarea_children_to_prop | python | reactive-python/reactpy | src/reactpy/transforms.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/transforms.py | MIT |
def select_element_to_reactjs(self, vdom: VdomDict) -> None:
"""Performs several transformations on the <select> element to make it ReactJS-compatible.
1. Convert the `selected` attribute on <option> is replaced with the ReactJS equivalent.
Namely, ReactJS uses props on the parent <select> ... | Performs several transformations on the <select> element to make it ReactJS-compatible.
1. Convert the `selected` attribute on <option> is replaced with the ReactJS equivalent.
Namely, ReactJS uses props on the parent <select> element to indicate which <option> is selected.
2. Sets the `val... | select_element_to_reactjs | python | reactive-python/reactpy | src/reactpy/transforms.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/transforms.py | MIT |
def input_element_value_prop_to_defaultValue(vdom: VdomDict) -> None:
"""ReactJS will complain that inputs are uncontrolled if defining the `value` prop,
so we use `defaultValue` instead. This has an added benefit of not deleting/overriding
any user input when a `string_to_reactpy` re-renders fi... | ReactJS will complain that inputs are uncontrolled if defining the `value` prop,
so we use `defaultValue` instead. This has an added benefit of not deleting/overriding
any user input when a `string_to_reactpy` re-renders fields that do not retain their `value`,
such as password fields. | input_element_value_prop_to_defaultValue | python | reactive-python/reactpy | src/reactpy/transforms.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/transforms.py | MIT |
def infer_key_from_attributes(vdom: VdomDict) -> None:
"""Infer the ReactJS `key` by looking at any attributes that should be unique."""
attributes = vdom.get("attributes", {})
if not attributes:
return
# Infer 'key' from 'attributes.key'
key = attributes.get("key", ... | Infer the ReactJS `key` by looking at any attributes that should be unique. | infer_key_from_attributes | python | reactive-python/reactpy | src/reactpy/transforms.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/transforms.py | MIT |
def intercept_link_clicks(self, vdom: VdomDict) -> None:
"""Intercepts anchor link clicks and prevents the default behavior.
This allows ReactPy-Router to handle the navigation instead of the browser."""
if vdom["tagName"] != "a" or not self._intercept_links:
return
vdom.set... | Intercepts anchor link clicks and prevents the default behavior.
This allows ReactPy-Router to handle the navigation instead of the browser. | intercept_link_clicks | python | reactive-python/reactpy | src/reactpy/transforms.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/transforms.py | MIT |
def _parse_options(self, vdom_or_any: Any) -> list[str]:
"""Parses a tree of elements to find all <option> elements with the 'selected' prop.
1. Sets the `value` prop on each <option> element so that ReactJS knows the identity of each element.
2. The 'selected' prop is removed, and this function... | Parses a tree of elements to find all <option> elements with the 'selected' prop.
1. Sets the `value` prop on each <option> element so that ReactJS knows the identity of each element.
2. The 'selected' prop is removed, and this function returns a list of selected elements. | _parse_options | python | reactive-python/reactpy | src/reactpy/transforms.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/transforms.py | MIT |
async def __aexit__(
self,
exc_type: type[Exception],
exc_value: Exception,
traceback: TracebackType,
) -> bool | None:
"""Clean up the view after its final render""" | Clean up the view after its final render | __aexit__ | python | reactive-python/reactpy | src/reactpy/types.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/types.py | MIT |
def set_current(self, new: _RefValue) -> _RefValue:
"""Set the current value and return what is now the old value
This is nice to use in ``lambda`` functions.
"""
old = self.current
self.current = new
return old | Set the current value and return what is now the old value
This is nice to use in ``lambda`` functions.
| set_current | python | reactive-python/reactpy | src/reactpy/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/utils.py | MIT |
def reactpy_to_string(root: VdomDict | ComponentType) -> str:
"""Convert a ReactPy component or `reactpy.html` element into an HTML string.
Parameters:
root: The ReactPy element to convert to a string.
"""
temp_container = etree.Element("__temp__")
if not isinstance(root, dict):
ro... | Convert a ReactPy component or `reactpy.html` element into an HTML string.
Parameters:
root: The ReactPy element to convert to a string.
| reactpy_to_string | python | reactive-python/reactpy | src/reactpy/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/utils.py | MIT |
def string_to_reactpy(
html: str,
*transforms: _ModelTransform,
strict: bool = True,
intercept_links: bool = True,
) -> VdomDict:
"""Transform HTML string into a ReactPy DOM model. ReactJS keys can be provided to HTML elements
using a ``key=...`` attribute within your HTML tag.
Parameters:
... | Transform HTML string into a ReactPy DOM model. ReactJS keys can be provided to HTML elements
using a ``key=...`` attribute within your HTML tag.
Parameters:
html:
The raw HTML as a string
transforms:
Function that takes a VDOM dictionary input and returns the new (mutat... | string_to_reactpy | python | reactive-python/reactpy | src/reactpy/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/utils.py | MIT |
def _etree_to_vdom(
node: etree._Element, transforms: Iterable[_ModelTransform], intercept_links: bool
) -> VdomDict:
"""Transform an lxml etree node into a DOM model."""
if not isinstance(node, etree._Element): # nocov
msg = f"Expected node to be a etree._Element, not {type(node).__name__}"
... | Transform an lxml etree node into a DOM model. | _etree_to_vdom | python | reactive-python/reactpy | src/reactpy/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/utils.py | MIT |
def _generate_vdom_children(
node: etree._Element, transforms: Iterable[_ModelTransform], intercept_links: bool
) -> list[VdomDict | str]:
"""Generates a list of VDOM children from an lxml node.
Inserts inner text and/or tail text in between VDOM children, if necessary.
"""
return ( # Get the inne... | Generates a list of VDOM children from an lxml node.
Inserts inner text and/or tail text in between VDOM children, if necessary.
| _generate_vdom_children | python | reactive-python/reactpy | src/reactpy/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/utils.py | MIT |
def component_to_vdom(component: ComponentType) -> VdomDict:
"""Convert the first render of a component into a VDOM dictionary"""
result = component.render()
if isinstance(result, dict):
return result
if hasattr(result, "render"):
return component_to_vdom(cast(ComponentType, result))
... | Convert the first render of a component into a VDOM dictionary | component_to_vdom | python | reactive-python/reactpy | src/reactpy/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/utils.py | MIT |
def _react_attribute_to_html(key: str, value: Any) -> tuple[str, str]:
"""Convert a React attribute to an HTML attribute string."""
if callable(value): # nocov
raise TypeError(f"Cannot convert callable attribute {key}={value} to HTML")
if key == "style":
if isinstance(value, dict):
... | Convert a React attribute to an HTML attribute string. | _react_attribute_to_html | python | reactive-python/reactpy | src/reactpy/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/utils.py | MIT |
def import_dotted_path(dotted_path: str) -> Any:
"""Imports a dotted path and returns the callable."""
if "." not in dotted_path:
raise ValueError(f'"{dotted_path}" is not a valid dotted path.')
module_name, component_name = dotted_path.rsplit(".", 1)
try:
module = import_module(module... | Imports a dotted path and returns the callable. | import_dotted_path | python | reactive-python/reactpy | src/reactpy/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/utils.py | MIT |
def image(
format: str,
value: str | bytes = "",
attributes: VdomAttributes | None = None,
) -> VdomDict:
"""Utility for constructing an image from a string or bytes
The source value will automatically be encoded to base64
"""
if format == "svg":
format = "svg+xml" # noqa: A001
... | Utility for constructing an image from a string or bytes
The source value will automatically be encoded to base64
| image | python | reactive-python/reactpy | src/reactpy/widgets.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/widgets.py | MIT |
def use_linked_inputs(
attributes: Sequence[dict[str, Any]],
on_change: Callable[[_Value], None] = lambda value: None,
cast: _CastFunc[_Value] = lambda value: value,
initial_value: str = "",
ignore_empty: bool = True,
) -> list[VdomDict]:
"""Return a list of linked inputs equal to the number of ... | Return a list of linked inputs equal to the number of given attributes.
Parameters:
attributes:
That attributes of each returned input element. If the number of generated
inputs is variable, you may need to assign each one a
:ref:`key <Organizing Items With Keys>` by inc... | use_linked_inputs | python | reactive-python/reactpy | src/reactpy/widgets.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/widgets.py | MIT |
def _fragment(
attributes: VdomAttributes,
children: Sequence[VdomChild],
key: Key | None,
event_handlers: EventHandlerDict,
) -> VdomDict:
"""An HTML fragment - this element will not appear in the DOM"""
attributes.pop("key", None)
if attributes or event_handlers:
msg = "Fragments c... | An HTML fragment - this element will not appear in the DOM | _fragment | python | reactive-python/reactpy | src/reactpy/_html.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_html.py | MIT |
def subscribe(self, handler: Callable[[_O], None]) -> Callable[[_O], None]:
"""Register a callback that will be triggered when this option changes"""
if not self.mutable:
msg = "Immutable options cannot be subscribed to."
raise TypeError(msg)
self._subscribers.append(hand... | Register a callback that will be triggered when this option changes | subscribe | python | reactive-python/reactpy | src/reactpy/_option.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_option.py | MIT |
def set_current(self, new: Any) -> None:
"""Set the value of this option
Raises a ``TypeError`` if this option is not :attr:`Option.mutable`.
"""
old = self.current
if new is old:
return None
if not self._mutable:
msg = f"{self} cannot be modifie... | Set the value of this option
Raises a ``TypeError`` if this option is not :attr:`Option.mutable`.
| set_current | python | reactive-python/reactpy | src/reactpy/_option.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_option.py | MIT |
def set_default(self, new: _O) -> _O:
"""Set the value of this option if not :meth:`Option.is_set`
Returns the current value (a la :meth:`dict.set_default`)
"""
if not self.is_set():
self.set_current(new)
return self._current | Set the value of this option if not :meth:`Option.is_set`
Returns the current value (a la :meth:`dict.set_default`)
| set_default | python | reactive-python/reactpy | src/reactpy/_option.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_option.py | MIT |
def unset(self) -> None:
"""Remove the current value, the default will be used until it is set again."""
if not self._mutable:
msg = f"{self} cannot be modified after initial load"
raise TypeError(msg)
old = self.current
if hasattr(self, "_current"):
d... | Remove the current value, the default will be used until it is set again. | unset | python | reactive-python/reactpy | src/reactpy/_option.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_option.py | MIT |
def component(
function: Callable[..., ComponentType | VdomDict | str | None],
) -> Callable[..., Component]:
"""A decorator for defining a new component.
Parameters:
function: The component's :meth:`reactpy.core.proto.ComponentType.render` function.
"""
sig = inspect.signature(function)
... | A decorator for defining a new component.
Parameters:
function: The component's :meth:`reactpy.core.proto.ComponentType.render` function.
| component | python | reactive-python/reactpy | src/reactpy/core/component.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/component.py | MIT |
def event(
function: Callable[..., Any] | None = None,
*,
stop_propagation: bool = False,
prevent_default: bool = False,
) -> EventHandler | Callable[[Callable[..., Any]], EventHandler]:
"""A decorator for constructing an :class:`EventHandler`.
While you're always free to add callbacks by assig... | A decorator for constructing an :class:`EventHandler`.
While you're always free to add callbacks by assigning them to an element's attributes
.. code-block:: python
element = reactpy.html.button({"onClick": my_callback})
You may want the ability to prevent the default action associated with the ... | event | python | reactive-python/reactpy | src/reactpy/core/events.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/events.py | MIT |
def to_event_handler_function(
function: Callable[..., Any],
positional_args: bool = True,
) -> EventHandlerFunc:
"""Make a :data:`~reactpy.core.proto.EventHandlerFunc` from a function or coroutine
Parameters:
function:
A function or coroutine accepting a number of positional argume... | Make a :data:`~reactpy.core.proto.EventHandlerFunc` from a function or coroutine
Parameters:
function:
A function or coroutine accepting a number of positional arguments.
positional_args:
Whether to pass the event parameters a positional args or as a list.
| to_event_handler_function | python | reactive-python/reactpy | src/reactpy/core/events.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/events.py | MIT |
def merge_event_handlers(
event_handlers: Sequence[EventHandlerType],
) -> EventHandlerType:
"""Merge multiple event handlers into one
Raises a ValueError if any handlers have conflicting
:attr:`~reactpy.core.proto.EventHandlerType.stop_propagation` or
:attr:`~reactpy.core.proto.EventHandlerType.pr... | Merge multiple event handlers into one
Raises a ValueError if any handlers have conflicting
:attr:`~reactpy.core.proto.EventHandlerType.stop_propagation` or
:attr:`~reactpy.core.proto.EventHandlerType.prevent_default` attributes.
| merge_event_handlers | python | reactive-python/reactpy | src/reactpy/core/events.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/events.py | MIT |
def merge_event_handler_funcs(
functions: Sequence[EventHandlerFunc],
) -> EventHandlerFunc:
"""Make one event handler function from many"""
if not functions:
msg = "No event handler functions to merge"
raise ValueError(msg)
elif len(functions) == 1:
return functions[0]
asyn... | Make one event handler function from many | merge_event_handler_funcs | python | reactive-python/reactpy | src/reactpy/core/events.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/events.py | MIT |
def use_state(initial_value: _Type | Callable[[], _Type]) -> State[_Type]:
"""See the full :ref:`Use State` docs for details
Parameters:
initial_value:
Defines the initial value of the state. A callable (accepting no arguments)
can be used as a constructor function to avoid re-c... | See the full :ref:`Use State` docs for details
Parameters:
initial_value:
Defines the initial value of the state. A callable (accepting no arguments)
can be used as a constructor function to avoid re-creating the initial value
on each render.
Returns:
A tupl... | use_state | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
def use_effect(
function: _SyncEffectFunc | None = None,
dependencies: Sequence[Any] | ellipsis | None = ...,
) -> Callable[[_SyncEffectFunc], None] | None:
"""
A hook that manages an synchronous side effect in a React-like component.
This hook allows you to run a synchronous function as a side eff... |
A hook that manages an synchronous side effect in a React-like component.
This hook allows you to run a synchronous function as a side effect and
ensures that the effect is properly cleaned up when the component is
re-rendered or unmounted.
Parameters:
function:
Applies the ef... | use_effect | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
def use_async_effect(
function: _AsyncEffectFunc | None = None,
dependencies: Sequence[Any] | ellipsis | None = ...,
shutdown_timeout: float = 0.1,
) -> Callable[[_AsyncEffectFunc], None] | None:
"""
A hook that manages an asynchronous side effect in a React-like component.
This hook allows you... |
A hook that manages an asynchronous side effect in a React-like component.
This hook allows you to run an asynchronous function as a side effect and
ensures that the effect is properly cleaned up when the component is
re-rendered or unmounted.
Args:
function:
Applies the effec... | use_async_effect | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
def use_debug_value(
message: Any | Callable[[], Any],
dependencies: Sequence[Any] | ellipsis | None = ...,
) -> None:
"""Log debug information when the given message changes.
.. note::
This hook only logs if :data:`~reactpy.config.REACTPY_DEBUG` is active.
Unlike other hooks, a message is... | Log debug information when the given message changes.
.. note::
This hook only logs if :data:`~reactpy.config.REACTPY_DEBUG` is active.
Unlike other hooks, a message is considered to have changed if the old and new
values are ``!=``. Because this comparison is performed on every render of the
... | use_debug_value | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
def create_context(default_value: _Type) -> Context[_Type]:
"""Return a new context type for use in :func:`use_context`"""
def context(
*children: Any,
value: _Type = default_value,
key: Key | None = None,
) -> _ContextProvider[_Type]:
return _ContextProvider(
*c... | Return a new context type for use in :func:`use_context` | create_context | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
def use_context(context: Context[_Type]) -> _Type:
"""Get the current value for the given context type.
See the full :ref:`Use Context` docs for more information.
"""
hook = HOOK_STACK.current_hook()
provider = hook.get_context_provider(context)
if provider is None:
# same assertions b... | Get the current value for the given context type.
See the full :ref:`Use Context` docs for more information.
| use_context | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
def use_connection() -> Connection[Any]:
"""Get the current :class:`~reactpy.backend.types.Connection`."""
conn = use_context(ConnectionContext)
if conn is None: # nocov
msg = "No backend established a connection."
raise RuntimeError(msg)
return conn | Get the current :class:`~reactpy.backend.types.Connection`. | use_connection | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
def use_reducer(
reducer: Callable[[_Type, _ActionType], _Type],
initial_value: _Type,
) -> tuple[_Type, Callable[[_ActionType], None]]:
"""See the full :ref:`Use Reducer` docs for details
Parameters:
reducer:
A function which applies an action to the current state in order to
... | See the full :ref:`Use Reducer` docs for details
Parameters:
reducer:
A function which applies an action to the current state in order to
produce the next state.
initial_value:
The initial state value (same as for :func:`use_state`)
Returns:
A tuple ... | use_reducer | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
def use_callback(
function: _CallbackFunc | None = None,
dependencies: Sequence[Any] | ellipsis | None = ...,
) -> _CallbackFunc | Callable[[_CallbackFunc], _CallbackFunc]:
"""See the full :ref:`Use Callback` docs for details
Parameters:
function:
The function whose identity will be... | See the full :ref:`Use Callback` docs for details
Parameters:
function:
The function whose identity will be preserved
dependencies:
Dependencies of the callback. The identity the ``function`` will be updated
if the identity of any value in the given sequence chan... | use_callback | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
def use_memo(
function: Callable[[], _Type] | None = None,
dependencies: Sequence[Any] | ellipsis | None = ...,
) -> _Type | Callable[[Callable[[], _Type]], _Type]:
"""See the full :ref:`Use Memo` docs for details
Parameters:
function:
The function to be memoized.
dependenci... | See the full :ref:`Use Memo` docs for details
Parameters:
function:
The function to be memoized.
dependencies:
Dependencies for the memoized function. The memo will only be recomputed if
the identity of any value in the given sequence changes (i.e. their
... | use_memo | python | reactive-python/reactpy | src/reactpy/core/hooks.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/hooks.py | MIT |
async def deliver(self, event: LayoutEventMessage | dict[str, Any]) -> None:
"""Dispatch an event to the targeted handler"""
# It is possible for an element in the frontend to produce an event
# associated with a backend model that has been deleted. We only handle
# events if the element... | Dispatch an event to the targeted handler | deliver | python | reactive-python/reactpy | src/reactpy/core/layout.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/layout.py | MIT |
async def _serial_render(self) -> LayoutUpdateMessage: # nocov
"""Await the next available render. This will block until a component is updated"""
while True:
model_state_id = await self._rendering_queue.get()
try:
model_state = self._model_states_by_life_cycle_s... | Await the next available render. This will block until a component is updated | _serial_render | python | reactive-python/reactpy | src/reactpy/core/layout.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/layout.py | MIT |
async def _parallel_render(self) -> LayoutUpdateMessage:
"""Await to fetch the first completed render within our asyncio task group.
We use the `asyncio.tasks.wait` API in order to return the first completed task.
"""
await self._render_tasks_ready.acquire()
done, _ = await wait(... | Await to fetch the first completed render within our asyncio task group.
We use the `asyncio.tasks.wait` API in order to return the first completed task.
| _parallel_render | python | reactive-python/reactpy | src/reactpy/core/layout.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/layout.py | MIT |
async def serve_layout(
layout: LayoutType[
LayoutUpdateMessage | dict[str, Any], LayoutEventMessage | dict[str, Any]
],
send: SendCoroutine,
recv: RecvCoroutine,
) -> None:
"""Run a dispatch loop for a single view instance"""
async with layout:
try:
async with create... | Run a dispatch loop for a single view instance | serve_layout | python | reactive-python/reactpy | src/reactpy/core/serve.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/serve.py | MIT |
def validate_vdom_json(value: Any) -> VdomJson:
"""Validate serialized VDOM - see :attr:`VDOM_JSON_SCHEMA` for more info"""
_COMPILED_VDOM_VALIDATOR(value)
return cast(VdomJson, value) | Validate serialized VDOM - see :attr:`VDOM_JSON_SCHEMA` for more info | validate_vdom_json | python | reactive-python/reactpy | src/reactpy/core/vdom.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/vdom.py | MIT |
def __init__(
self,
tag_name: str,
/,
allow_children: bool = True,
custom_constructor: CustomVdomConstructor | None = None,
import_source: ImportSourceDict | None = None,
) -> None:
"""Initialize a VDOM constructor for the provided `tag_name`."""
self.... | Initialize a VDOM constructor for the provided `tag_name`. | __init__ | python | reactive-python/reactpy | src/reactpy/core/vdom.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/vdom.py | MIT |
def __getattr__(self, attr: str) -> Vdom:
"""Supports accessing nested web module components"""
if not self.import_source:
msg = "Nested components can only be accessed on web module components."
raise AttributeError(msg)
return Vdom(
f"{self.__name__}.{attr}"... | Supports accessing nested web module components | __getattr__ | python | reactive-python/reactpy | src/reactpy/core/vdom.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/vdom.py | MIT |
def __call__(
self, *attributes_and_children: VdomAttributes | VdomChildren
) -> VdomDict:
"""The entry point for the VDOM API, for example reactpy.html(<WE_ARE_HERE>)."""
attributes, children = separate_attributes_and_children(attributes_and_children)
key = attributes.get("key", Non... | The entry point for the VDOM API, for example reactpy.html(<WE_ARE_HERE>). | __call__ | python | reactive-python/reactpy | src/reactpy/core/vdom.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/vdom.py | MIT |
def use_state(self, function: Callable[[], T]) -> T:
"""Add state to this hook
If this hook has not yet rendered, the state is appended to the state tuple.
Otherwise, the state is retrieved from the tuple. This allows state to be
preserved across renders.
"""
if not self... | Add state to this hook
If this hook has not yet rendered, the state is appended to the state tuple.
Otherwise, the state is retrieved from the tuple. This allows state to be
preserved across renders.
| use_state | python | reactive-python/reactpy | src/reactpy/core/_life_cycle_hook.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/_life_cycle_hook.py | MIT |
def get_context_provider(
self, context: Context[T]
) -> ContextProviderType[T] | None:
"""Get a context provider for this hook of the given type
The context provider will have been set by a parent component. If no provider
is found, ``None`` is returned.
"""
return ... | Get a context provider for this hook of the given type
The context provider will have been set by a parent component. If no provider
is found, ``None`` is returned.
| get_context_provider | python | reactive-python/reactpy | src/reactpy/core/_life_cycle_hook.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/_life_cycle_hook.py | MIT |
async def affect_component_will_render(self, component: ComponentType) -> None:
"""The component is about to render"""
await self._render_access.acquire()
self._scheduled_render = False
self.component = component
self.set_current() | The component is about to render | affect_component_will_render | python | reactive-python/reactpy | src/reactpy/core/_life_cycle_hook.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/_life_cycle_hook.py | MIT |
async def affect_component_will_unmount(self) -> None:
"""The component is about to be removed from the layout"""
for stop in self._effect_stops:
stop.set()
self._effect_stops.clear()
try:
await gather(*self._effect_tasks)
except Exception:
log... | The component is about to be removed from the layout | affect_component_will_unmount | python | reactive-python/reactpy | src/reactpy/core/_life_cycle_hook.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/_life_cycle_hook.py | MIT |
def set_current(self) -> None:
"""Set this hook as the active hook in this thread
This method is called by a layout before entering the render method
of this hook's associated component.
"""
hook_stack = HOOK_STACK.get()
if hook_stack:
parent = hook_stack[-1]... | Set this hook as the active hook in this thread
This method is called by a layout before entering the render method
of this hook's associated component.
| set_current | python | reactive-python/reactpy | src/reactpy/core/_life_cycle_hook.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/_life_cycle_hook.py | MIT |
def unset_current(self) -> None:
"""Unset this hook as the active hook in this thread"""
if HOOK_STACK.get().pop() is not self:
raise RuntimeError("Hook stack is in an invalid state") # nocov | Unset this hook as the active hook in this thread | unset_current | python | reactive-python/reactpy | src/reactpy/core/_life_cycle_hook.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/core/_life_cycle_hook.py | MIT |
def import_components(dotted_paths: Iterable[str]) -> dict[str, Any]:
"""Imports a list of dotted paths and returns the callables."""
return {
dotted_path: import_dotted_path(dotted_path) for dotted_path in dotted_paths
} | Imports a list of dotted paths and returns the callables. | import_components | python | reactive-python/reactpy | src/reactpy/executors/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/utils.py | MIT |
def check_path(url_path: str) -> str: # nocov
"""Check that a path is valid URL path."""
if not url_path:
return "URL path must not be empty."
if not isinstance(url_path, str):
return "URL path is must be a string."
if not url_path.startswith("/"):
return "URL path must start wi... | Check that a path is valid URL path. | check_path | python | reactive-python/reactpy | src/reactpy/executors/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/utils.py | MIT |
def process_settings(settings: ReactPyConfig) -> None:
"""Process the settings and return the final configuration."""
from reactpy import config
for setting in settings:
config_name = f"REACTPY_{setting.upper()}"
config_object: Option[Any] | None = getattr(config, config_name, None)
... | Process the settings and return the final configuration. | process_settings | python | reactive-python/reactpy | src/reactpy/executors/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/utils.py | MIT |
def __init__(
self,
app: AsgiApp,
root_components: Iterable[str],
**settings: Unpack[ReactPyConfig],
) -> None:
"""Configure the ASGI app. Anything initialized in this method will be shared across all future requests.
Parameters:
app: The ASGI application... | Configure the ASGI app. Anything initialized in this method will be shared across all future requests.
Parameters:
app: The ASGI application to serve when the request does not match a ReactPy route.
root_components:
A list, set, or tuple containing the dotted path of you... | __init__ | python | reactive-python/reactpy | src/reactpy/executors/asgi/middleware.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/middleware.py | MIT |
async def __call__(
self, scope: AsgiScope, receive: AsgiReceive, send: AsgiSend
) -> None:
"""The ASGI entrypoint that determines whether ReactPy should route the
request to ourselves or to the user application."""
# URL routing for the ReactPy renderer
if scope["type"] == "... | The ASGI entrypoint that determines whether ReactPy should route the
request to ourselves or to the user application. | __call__ | python | reactive-python/reactpy | src/reactpy/executors/asgi/middleware.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/middleware.py | MIT |
async def __call__(
self,
scope: AsgiWebsocketScope,
receive: AsgiWebsocketReceive,
send: AsgiWebsocketSend,
) -> None:
"""ASGI app for rendering ReactPy Python components."""
# Start a loop that handles ASGI websocket events
async with ReactPyWebsocket(scope,... | ASGI app for rendering ReactPy Python components. | __call__ | python | reactive-python/reactpy | src/reactpy/executors/asgi/middleware.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/middleware.py | MIT |
async def run_dispatcher(self) -> None:
"""Async background task that renders ReactPy components over a websocket."""
try:
# Determine component to serve by analyzing the URL and/or class parameters.
if self.parent.multiple_root_components:
url_match = re.match(se... | Async background task that renders ReactPy components over a websocket. | run_dispatcher | python | reactive-python/reactpy | src/reactpy/executors/asgi/middleware.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/middleware.py | MIT |
async def __call__(
self, scope: AsgiHttpScope, receive: AsgiHttpReceive, send: AsgiHttpSend
) -> None:
"""ASGI app for ReactPy static files."""
if not self._static_file_server:
self._static_file_server = ServeStaticASGI(
Error404App(),
root=self.p... | ASGI app for ReactPy static files. | __call__ | python | reactive-python/reactpy | src/reactpy/executors/asgi/middleware.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/middleware.py | MIT |
async def __call__(
self, scope: AsgiHttpScope, receive: AsgiHttpReceive, send: AsgiHttpSend
) -> None:
"""ASGI app for ReactPy web modules."""
if not self._static_file_server:
self._static_file_server = ServeStaticASGI(
Error404App(),
root=self.pa... | ASGI app for ReactPy web modules. | __call__ | python | reactive-python/reactpy | src/reactpy/executors/asgi/middleware.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/middleware.py | MIT |
def __init__(
self,
*file_paths: str | Path,
extra_py: Sequence[str] = (),
extra_js: dict[str, str] | None = None,
pyscript_config: dict[str, Any] | None = None,
root_name: str = "root",
initial: str | VdomDict = "",
http_headers: dict[str, str] | None = N... | Variant of ReactPy's standalone that only performs Client-Side Rendering (CSR) via
PyScript (using the Pyodide interpreter).
This ASGI webserver is only used to serve the initial HTML document and static files.
Parameters:
file_paths:
File path(s) to the Python file... | __init__ | python | reactive-python/reactpy | src/reactpy/executors/asgi/pyscript.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/pyscript.py | MIT |
def render_index_html(self) -> None:
"""Process the index.html and store the results in this class."""
head_content = vdom_head_to_html(self.parent.html_head)
pyscript_setup = pyscript_setup_html(
extra_py=self.parent.extra_py,
extra_js=self.parent.extra_js,
c... | Process the index.html and store the results in this class. | render_index_html | python | reactive-python/reactpy | src/reactpy/executors/asgi/pyscript.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/pyscript.py | MIT |
def __init__(
self,
root_component: RootComponentConstructor,
*,
http_headers: dict[str, str] | None = None,
html_head: VdomDict | None = None,
html_lang: str = "en",
pyscript_setup: bool = False,
pyscript_options: PyScriptOptions | None = None,
**... | ReactPy's standalone ASGI application.
Parameters:
root_component: The root component to render. This app is typically a single page application.
http_headers: Additional headers to include in the HTTP response for the base HTML document.
html_head: Additional head elements ... | __init__ | python | reactive-python/reactpy | src/reactpy/executors/asgi/standalone.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/standalone.py | MIT |
def match_extra_paths(self, scope: AsgiScope) -> AsgiApp | None:
"""Method override to match user-provided HTTP/Websocket routes."""
if scope["type"] == "lifespan":
return self.extra_lifespan_app
routing_dictionary = {}
if scope["type"] == "http":
routing_diction... | Method override to match user-provided HTTP/Websocket routes. | match_extra_paths | python | reactive-python/reactpy | src/reactpy/executors/asgi/standalone.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/standalone.py | MIT |
def route(
self,
path: str,
type: Literal["http", "websocket"] = "http",
) -> (
Callable[[AsgiV3HttpApp | str], AsgiApp]
| Callable[[AsgiV3WebsocketApp | str], AsgiApp]
):
"""Interface that allows user to define their own HTTP/Websocket routes
within the c... | Interface that allows user to define their own HTTP/Websocket routes
within the current ReactPy application.
Parameters:
path: The URL route to match, using regex format.
type: The protocol to route for. Can be 'http' or 'websocket'.
| route | python | reactive-python/reactpy | src/reactpy/executors/asgi/standalone.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/standalone.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.