Python API#
_console
#
ast_utils
#
rewrite_camel_case_props
#
rewrite_keys
#
backend
#
_common
#
- async reactpy.backend._common.serve_with_uvicorn(app, host, port, started)[source]#
Run a development server for an ASGI application
- Parameters
app (ASGIApplication | Any) β
host (str) β
port (int) β
started (asyncio.Event | None) β
- Return type
None
- reactpy.backend._common.safe_client_build_dir_path(path)[source]#
Prevent path traversal out of
CLIENT_BUILD_DIR
- Parameters
path (str) β
- Return type
- reactpy.backend._common.safe_web_modules_dir_path(path)[source]#
Prevent path traversal out of
reactpy.config.REACTPY_WEB_MODULES_DIR
- Parameters
path (str) β
- Return type
- reactpy.backend._common.traversal_safe_path(root, *unsafe)[source]#
Raise a
ValueError
if theunsafe
path resolves outside the root dir.
- class reactpy.backend._common.CommonOptions(head=({'tagName': 'title', 'children': ['ReactPy']}, {'tagName': 'link', 'attributes': {'rel': 'icon', 'href': '/_reactpy/assets/reactpy-logo.ico', 'type': 'image/x-icon'}}), url_prefix='', serve_index_route=True)[source]#
Bases:
object
Options for ReactPyβs built-in backed server implementations
- Parameters
- Return type
None
- head: Sequence[VdomDict] | VdomDict | str = ({'tagName': 'title', 'children': ['ReactPy']}, {'tagName': 'link', 'attributes': {'rel': 'icon', 'href': '/_reactpy/assets/reactpy-logo.ico', 'type': 'image/x-icon'}})#
Add elements to the
<head>
of the application.For example, this can be used to customize the title of the page, link extra scripts, or load stylesheets.
default
#
- class reactpy.backend.default.Options(*args, **kwds)[source]#
Bases:
object
Configuration options that can be provided to the backend. This definition should not be used/instantiated. It exists only for type hinting purposes.
- Parameters
args (Any) β
kwds (Any) β
- Return type
NoReturn
- reactpy.backend.default.configure(app, component, options=None)[source]#
Configure the given app instance to display the given component
- Parameters
app (Any) β
component (RootComponentConstructor) β
options (None) β
- Return type
None
- reactpy.backend.default.create_development_app()[source]#
Create an application instance for development purposes
- Return type
- async reactpy.backend.default.serve_development_app(app, host, port, started=None)[source]#
Run an application using a development server
- Parameters
app (Any) β
host (str) β
port (int) β
started (asyncio.Event | None) β
- Return type
None
fastapi
#
flask
#
- class reactpy.backend.flask.Options(head=({'tagName': 'title', 'children': ['ReactPy']}, {'tagName': 'link', 'attributes': {'rel': 'icon', 'href': '/_reactpy/assets/reactpy-logo.ico', 'type': 'image/x-icon'}}), url_prefix='', serve_index_route=True, cors=False)[source]#
Bases:
reactpy.backend._common.CommonOptions
Render server config for
reactpy.backend.flask.configure()
- Parameters
- Return type
None
- reactpy.backend.flask.configure(app, component, options=None)[source]#
Configure the necessary ReactPy routes on the given app.
- Parameters
app (Flask) β An application instance
component (RootComponentConstructor) β A component constructor
options (Options | None) β Options for configuring server behavior
- Return type
None
- reactpy.backend.flask.create_development_app()[source]#
Create an application instance for development purposes
- Return type
- async reactpy.backend.flask.serve_development_app(app, host, port, started=None)[source]#
Run a development server for FastAPI
- Parameters
app (Flask) β
host (str) β
port (int) β
started (asyncio.Event | None) β
- Return type
None
- reactpy.backend.flask.use_websocket()[source]#
A handle to the current websocket
- Return type
simple_websocket.ws.Server
- reactpy.backend.flask.use_connection()[source]#
Get the current
Connection
- Return type
reactpy.backend.types.Connection[reactpy.backend.flask._FlaskCarrier]
hooks
#
- reactpy.backend.hooks.use_connection()[source]#
Get the current
Connection
.- Return type
- reactpy.backend.hooks.use_scope()[source]#
Get the current
Connection
βs scope.- Return type
- reactpy.backend.hooks.use_location()[source]#
Get the current
Connection
βs location.- Return type
sanic
#
- class reactpy.backend.sanic.Options(head=({'tagName': 'title', 'children': ['ReactPy']}, {'tagName': 'link', 'attributes': {'rel': 'icon', 'href': '/_reactpy/assets/reactpy-logo.ico', 'type': 'image/x-icon'}}), url_prefix='', serve_index_route=True, cors=False)[source]#
Bases:
reactpy.backend._common.CommonOptions
Render server config for
reactpy.backend.sanic.configure()
- Parameters
- Return type
None
- reactpy.backend.sanic.configure(app, component, options=None)[source]#
Configure an application instance to display the given component
- Parameters
app (Sanic[Any, Any]) β
component (RootComponentConstructor) β
options (Options | None) β
- Return type
None
- reactpy.backend.sanic.create_development_app()[source]#
Return a
Sanic
app instance in test mode- Return type
Sanic[Any, Any]
- async reactpy.backend.sanic.serve_development_app(app, host, port, started=None)[source]#
Run a development server for
sanic
- Parameters
app (Sanic[Any, Any]) β
host (str) β
port (int) β
started (asyncio.Event | None) β
- Return type
None
- reactpy.backend.sanic.use_request()[source]#
Get the current
Request
- Return type
request.Request[Any, Any]
- reactpy.backend.sanic.use_websocket()[source]#
Get the current websocket
- Return type
sanic.server.websockets.connection.WebSocketConnection
- reactpy.backend.sanic.use_connection()[source]#
Get the current
Connection
- Return type
reactpy.backend.types.Connection[reactpy.backend.sanic._SanicCarrier]
starlette
#
- class reactpy.backend.starlette.Options(head=({'tagName': 'title', 'children': ['ReactPy']}, {'tagName': 'link', 'attributes': {'rel': 'icon', 'href': '/_reactpy/assets/reactpy-logo.ico', 'type': 'image/x-icon'}}), url_prefix='', serve_index_route=True, cors=False)[source]#
Bases:
reactpy.backend._common.CommonOptions
Render server config for
reactpy.backend.starlette.configure()
- Parameters
- Return type
None
- reactpy.backend.starlette.configure(app, component, options=None)[source]#
Configure the necessary ReactPy routes on the given app.
- Parameters
app (Starlette) β An application instance
component (RootComponentConstructor) β A component constructor
options (Options | None) β Options for configuring server behavior
- Return type
None
- reactpy.backend.starlette.create_development_app()[source]#
Return a
Starlette
app instance in debug mode- Return type
starlette.applications.Starlette
- async reactpy.backend.starlette.serve_development_app(app, host, port, started=None)[source]#
Run a development server for starlette
- Parameters
app (Starlette) β
host (str) β
port (int) β
started (asyncio.Event | None) β
- Return type
None
tornado
#
- reactpy.backend.tornado.configure(app, component, options=None)[source]#
Configure the necessary ReactPy routes on the given app.
- Parameters
app (Application) β An application instance
component (ComponentConstructor) β A component constructor
options (CommonOptions | None) β Options for configuring server behavior
- Return type
None
- class reactpy.backend.tornado.IndexHandler(application, request, **kwargs)[source]#
Bases:
tornado.web.RequestHandler
- Parameters
application (Application) β
request (tornado.httputil.HTTPServerRequest) β
kwargs (Any) β
- Return type
None
- class reactpy.backend.tornado.ModelStreamHandler(application, request, **kwargs)[source]#
Bases:
tornado.websocket.WebSocketHandler
A web-socket handler that serves up a new model stream to each new client
- Parameters
application (tornado.web.Application) β
request (tornado.httputil.HTTPServerRequest) β
kwargs (Any) β
- Return type
None
- async open(path='', *args, **kwargs)[source]#
Invoked when a new WebSocket is opened.
The arguments to open are extracted from the tornado.web.URLSpec regular expression, just like the arguments to tornado.web.RequestHandler.get.
open may be a coroutine. on_message will not be called until open has returned.
Changed in version 5.1:
open
may be a coroutine.
- async on_message(message)[source]#
Handle incoming messages on the WebSocket
This method must be overridden.
Changed in version 4.5:
on_message
can be a coroutine.
- on_close()[source]#
Invoked when the WebSocket is closed.
If the connection was closed cleanly and a status code or reason phrase was supplied, these values will be available as the attributes
self.close_code
andself.close_reason
.Changed in version 4.0: Added
close_code
andclose_reason
attributes.- Return type
None
types
#
- class reactpy.backend.types.BackendType(*args, **kwargs)[source]#
Bases:
Protocol
[reactpy.backend.types._App
]Common interface for built-in web server/framework integrations
- Options: Callable[[...], Any]#
A constructor for options passed to
BackendType.configure()
- configure(app, component, options=None)[source]#
Configure the given app instance to display the given component
- Parameters
app (_App) β
component (RootComponentConstructor) β
options (Any | None) β
- Return type
None
- create_development_app()[source]#
Create an application instance for development purposes
- Return type
reactpy.backend.types._App
- async serve_development_app(app, host, port, started=None)[source]#
Run an application using a development server
- Parameters
app (_App) β
host (str) β
port (int) β
started (asyncio.Event | None) β
- Return type
None
- class reactpy.backend.types.Connection(scope, location, carrier)[source]#
Bases:
Generic
[reactpy.backend.types._Carrier
]Represents a connection with a client
- Parameters
scope (collections.abc.MutableMapping[str, Any]) β
location (reactpy.backend.types.Location) β
carrier (reactpy.backend.types._Carrier) β
- Return type
None
- scope: collections.abc.MutableMapping[str, Any]#
An ASGI scope or WSGI environment dictionary
- location: reactpy.backend.types.Location#
The current location (URL)
- carrier: reactpy.backend.types._Carrier#
How the connection is mediated. For example, a request or websocket.
This typically depends on the backend implementation.
utils
#
- reactpy.backend.utils.run(component, host='127.0.0.1', port=None, implementation=None)[source]#
Run a component with a development server
- Parameters
component (RootComponentConstructor) β
host (str) β
port (int | None) β
implementation (BackendType[Any] | None) β
- Return type
None
- reactpy.backend.utils.find_available_port(host, port_min=8000, port_max=9000)[source]#
Get a port thatβs available for the given host and port range
- reactpy.backend.utils.all_implementations()[source]#
Yield all available server implementations
- Return type
collections.abc.Iterator[reactpy.backend.types.BackendType[Any]]
core
#
_f_back
#
_life_cycle_hook
#
- reactpy.core._life_cycle_hook.current_hook()[source]#
Get the current
LifeCycleHook
- Return type
- class reactpy.core._life_cycle_hook.LifeCycleHook(schedule_render)[source]#
Bases:
object
An object which manages the βlife cycleβ of a layout component.
The βlife cycleβ of a component is the set of events which occur from the time a component is first rendered until it is removed from the layout. The life cycle is ultimately driven by the layout itself, but components can βhookβ into those events to perform actions. Components gain access to their own life cycle hook by calling
current_hook()
. They can then perform actions such as:Adding state via
use_state()
Adding effects via
add_effect()
Setting or getting context providers via
LifeCycleHook.set_context_provider()
andget_context_provider()
respectively.
Components can request access to their own life cycle events and state through hooks while
LayoutType
objects drive drive the life cycle forward by triggering events and rendering view changes.Example
If removed from the complexities of a layout, a very simplified full life cycle for a single component with no child components would look a bit like this:
from reactpy.core._life_cycle_hook import LifeCycleHook from reactpy.core.hooks import current_hook # this function will come from a layout implementation schedule_render = lambda: ... # --- start life cycle --- hook = LifeCycleHook(schedule_render) # --- start render cycle --- component = ... await hook.affect_component_will_render(component) try: # render the component ... # the component may access the current hook assert current_hook() is hook # and save state or add effects current_hook().use_state(lambda: ...) async def my_effect(stop_event): ... current_hook().add_effect(my_effect) finally: await hook.affect_component_did_render() # This should only be called after the full set of changes associated with a # given render have been completed. await hook.affect_layout_did_render() # Typically an event occurs and a new render is scheduled, thus beginning # the render cycle anew. hook.schedule_render() # --- end render cycle --- hook.affect_component_will_unmount() del hook # --- end render cycle ---
- Parameters
schedule_render (Callable[[], None]) β
- Return type
None
- use_state(function)[source]#
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.
- Parameters
function (Callable[[], reactpy.core._life_cycle_hook.T]) β
- Return type
reactpy.core._life_cycle_hook.T
- add_effect(effect_func)[source]#
Add an effect to this hook
A task to run the effect is created when the component is done rendering. When the component will be unmounted, the event passed to the effect is triggered and the task is awaited. The effect should eventually halt after the event is triggered.
- Parameters
effect_func (reactpy.core._life_cycle_hook.EffectFunc) β
- Return type
None
- set_context_provider(provider)[source]#
Set a context provider for this hook
The context provider will be used to provide state to any child components of this hookβs component which request a context provider of the same type.
- Parameters
provider (reactpy.core.types.ContextProviderType[Any]) β
- Return type
None
- get_context_provider(context)[source]#
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.- Parameters
context (Context[T]) β
- Return type
ContextProviderType[T] | None
- async affect_component_will_render(component)[source]#
The component is about to render
- Parameters
component (reactpy.core.types.ComponentType) β
- Return type
None
- async affect_component_will_unmount()[source]#
The component is about to be removed from the layout
- Return type
None
_thread_local
#
component
#
- reactpy.core.component.component(function)[source]#
A decorator for defining a new component.
- Parameters
function (Callable[..., ComponentType | VdomDict | str | None]) β The componentβs
reactpy.core.proto.ComponentType.render()
function.- Return type
Callable[β¦, Component]
- class reactpy.core.component.Component(function, key, args, kwargs, sig)[source]#
Bases:
object
An object for rending component models.
- Parameters
function (Callable[..., ComponentType | VdomDict | str | None]) β
key (Any | None) β
args (tuple[Any, ...]) β
sig (inspect.Signature) β
- Return type
None
events
#
- reactpy.core.events.event(function: Callable[[...], Any], *, stop_propagation: bool = False, prevent_default: bool = False) reactpy.core.events.EventHandler [source]#
- reactpy.core.events.event(function: Literal[None] = None, *, stop_propagation: bool = False, prevent_default: bool = False) Callable[[Callable[[...], Any]], reactpy.core.events.EventHandler]
A decorator for constructing an
EventHandler
.While youβre always free to add callbacks by assigning them to an elementβs attributes
element = reactpy.html.button({"onClick": my_callback})
You may want the ability to prevent the default action associated with the event from taking place, or stopping the event from propagating up the DOM. This decorator allows you to add that functionality to your callbacks.
@event(stop_propagation=True, prevent_default=True) def my_callback(*data): ... element = reactpy.html.button({"onClick": my_callback})
- Parameters
function β A function or coroutine responsible for handling the event.
stop_propagation β Block the event from propagating further up the DOM.
prevent_default β Stops the default actional associate with the event from taking place.
- class reactpy.core.events.EventHandler(function, stop_propagation=False, prevent_default=False, target=None)[source]#
Bases:
object
Turn a function or coroutine into an event handler
- Parameters
function (EventHandlerFunc) β The function or coroutine which handles the event.
stop_propagation (bool) β Block the event from propagating further up the DOM.
prevent_default (bool) β Stops the default action associate with the event from taking place.
target (str | None) β A unique identifier for this event handler (auto-generated by default)
- Return type
None
- reactpy.core.events.to_event_handler_function(function, positional_args=True)[source]#
Make a
EventHandlerFunc
from a function or coroutine- Parameters
- Return type
- reactpy.core.events.merge_event_handlers(event_handlers)[source]#
Merge multiple event handlers into one
Raises a ValueError if any handlers have conflicting
stop_propagation
orprevent_default
attributes.- Parameters
event_handlers (collections.abc.Sequence[reactpy.core.types.EventHandlerType]) β
- Return type
- reactpy.core.events.merge_event_handler_funcs(functions)[source]#
Make one event handler function from many
- Parameters
functions (collections.abc.Sequence[reactpy.core.types.EventHandlerFunc]) β
- Return type
hooks
#
- reactpy.core.hooks.use_state(initial_value: Callable[[], reactpy.core.hooks._Type]) reactpy.core.types.State[reactpy.core.hooks._Type] [source]#
- reactpy.core.hooks.use_state(initial_value: reactpy.core.hooks._Type) reactpy.core.types.State[reactpy.core.hooks._Type]
See the full 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 tuple containing the current state and a function to update it.
- reactpy.core.hooks.use_effect(function: None = None, dependencies: Sequence[Any] | ellipsis | None = Ellipsis) Callable[[_EffectApplyFunc], None] [source]#
- reactpy.core.hooks.use_effect(function: _EffectApplyFunc, dependencies: Sequence[Any] | ellipsis | None = Ellipsis) None
See the full Use Effect docs for details
- Parameters
function β Applies the effect and can return a clean-up function
dependencies β Dependencies for the effect. The effect will only trigger if the identity of any value in the given sequence changes (i.e. their
id()
is different). By default these are inferred based on local variables that are referenced by the given function.
- Returns
If not function is provided, a decorator. Otherwise
None
.
- reactpy.core.hooks.use_debug_value(message, dependencies=Ellipsis)[source]#
Log debug information when the given message changes.
Note
This hook only logs if
REACTPY_DEBUG_MODE
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 component, it may be worth considering the performance cost in some situations.- Parameters
message (Any | Callable[[], Any]) β The value to log or a memoized function for generating the value.
dependencies (Sequence[Any] | ellipsis | None) β Dependencies for the memoized function. The message will only be recomputed if the identity of any value in the given sequence changes (i.e. their
id()
is different). By default these are inferred based on local variables that are referenced by the given function.
- Return type
None
- reactpy.core.hooks.create_context(default_value)[source]#
Return a new context type for use in
use_context()
- Parameters
default_value (reactpy.core.hooks._Type) β
- Return type
reactpy.core.types.Context[reactpy.core.hooks._Type]
- reactpy.core.hooks.use_context(context)[source]#
Get the current value for the given context type.
See the full Use Context docs for more information.
- Parameters
context (reactpy.core.types.Context[reactpy.core.hooks._Type]) β
- Return type
reactpy.core.hooks._Type
- reactpy.core.hooks.use_connection()[source]#
Get the current
Connection
.- Return type
- reactpy.core.hooks.use_scope()[source]#
Get the current
Connection
βs scope.- Return type
- reactpy.core.hooks.use_location()[source]#
Get the current
Connection
βs location.- Return type
- reactpy.core.hooks.use_reducer(reducer, initial_value)[source]#
See the full Use Reducer docs for details
- Parameters
reducer (Callable[[reactpy.core.hooks._Type, reactpy.core.hooks._ActionType], reactpy.core.hooks._Type]) β A function which applies an action to the current state in order to produce the next state.
initial_value (reactpy.core.hooks._Type) β The initial state value (same as for
use_state()
)
- Returns
A tuple containing the current state and a function to change it with an action
- Return type
- reactpy.core.hooks.use_callback(function: None = None, dependencies: Sequence[Any] | ellipsis | None = Ellipsis) Callable[[reactpy.core.hooks._CallbackFunc], reactpy.core.hooks._CallbackFunc] [source]#
- reactpy.core.hooks.use_callback(function: reactpy.core.hooks._CallbackFunc, dependencies: Sequence[Any] | ellipsis | None = Ellipsis) reactpy.core.hooks._CallbackFunc
See the full 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 changes (i.e. theirid()
is different). By default these are inferred based on local variables that are referenced by the given function.
- Returns
The current function
- reactpy.core.hooks.use_memo(function: None = None, dependencies: Sequence[Any] | ellipsis | None = Ellipsis) reactpy.core.hooks._LambdaCaller [source]#
- reactpy.core.hooks.use_memo(function: Callable[[], reactpy.core.hooks._Type], dependencies: Sequence[Any] | ellipsis | None = Ellipsis) reactpy.core.hooks._Type
See the full 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
id()
is different). By default these are inferred based on local variables that are referenced by the given function.
- Returns
The current state
- reactpy.core.hooks.use_ref(initial_value)[source]#
See the full Use State docs for details
- Parameters
initial_value (reactpy.core.hooks._Type) β The value initially assigned to the reference.
- Returns
A
Ref
object.- Return type
reactpy.utils.Ref[reactpy.core.hooks._Type]
layout
#
- class reactpy.core.layout.Layout(root)[source]#
Bases:
object
Responsible for βrenderingβ components. That is, turning them into VDOM.
- Parameters
root (ComponentType) β
- Return type
None
- async deliver(event)[source]#
Dispatch an event to the targeted handler
- Parameters
event (reactpy.core.types.LayoutEventMessage) β
- Return type
None
serve
#
- reactpy.core.serve.SendCoroutine#
Send model patches given by a dispatcher
alias of
Callable
[[reactpy.core.types.LayoutUpdateMessage
],collections.abc.Awaitable
[None
]]
- reactpy.core.serve.RecvCoroutine#
Called by a dispatcher to return a
reactpy.core.layout.LayoutEventMessage
The event will then trigger an
reactpy.core.proto.EventHandlerType
in a layout.alias of
Callable
[[],collections.abc.Awaitable
[reactpy.core.types.LayoutEventMessage
]]
- exception reactpy.core.serve.Stop[source]#
Bases:
BaseException
Deprecated
Stop serving changes and events
Raising this error will tell dispatchers to gracefully exit. Typically this is called by code running inside a layout to tell it to stop rendering.
- async reactpy.core.serve.serve_layout(layout, send, recv)[source]#
Run a dispatch loop for a single view instance
- Parameters
layout (reactpy.core.types.LayoutType[reactpy.core.types.LayoutUpdateMessage, reactpy.core.types.LayoutEventMessage]) β
send (Callable[[reactpy.core.types.LayoutUpdateMessage], collections.abc.Awaitable[None]]) β
recv (Callable[[], collections.abc.Awaitable[reactpy.core.types.LayoutEventMessage]]) β
- Return type
None
types
#
- class reactpy.core.types.State(value, set_value)[source]#
Bases:
tuple
- value: _Type#
Alias for field number 0
- reactpy.core.types.ComponentConstructor#
Simple function returning a new component
alias of
Callable
[[β¦],ComponentType
]
- reactpy.core.types.RootComponentConstructor#
The root component should be constructed by a function accepting no arguments.
alias of
Callable
[[],ComponentType
]
- class reactpy.core.types.ComponentType(*args, **kwargs)[source]#
Bases:
Protocol
The expected interface for all component-like objects
- type: Any#
The function or class defining the behavior of this component
This is used to see if two component instances share the same definition.
- render()[source]#
Render the componentβs view model.
- Return type
VdomDict | ComponentType | str | None
- class reactpy.core.types.LayoutType(*args, **kwargs)[source]#
Bases:
Protocol
[reactpy.core.types._Render_co
,reactpy.core.types._Event_contra
]Renders and delivers, updates to views and events to handlers, respectively
- reactpy.core.types.VdomChild: TypeAlias = 'ComponentType | VdomDict | str | None | Any'#
A single child element of a
VdomDict
- reactpy.core.types.VdomChildren: TypeAlias = 'Sequence[VdomChild] | VdomChild'#
Describes a series of
VdomChild
elements
- class reactpy.core.types.VdomDict(_typename, _fields=None, /, **kwargs)[source]#
Bases:
reactpy.core.types._VdomDictRequired
,reactpy.core.types._VdomDictOptional
A VDOM dictionary
- class reactpy.core.types.ImportSourceDict(_typename, _fields=None, /, **kwargs)[source]#
Bases:
typing_extensions.TypedDict
- class reactpy.core.types.VdomJson(_typename, _fields=None, /, **kwargs)[source]#
Bases:
reactpy.core.types._RequiredVdomJson
,reactpy.core.types._OptionalVdomJson
A JSON serializable form of
VdomDict
matching theVDOM_JSON_SCHEMA
- reactpy.core.types.EventHandlerMapping#
A generic mapping between event names to their handlers
- reactpy.core.types.EventHandlerDict: TypeAlias = 'dict[str, EventHandlerType]'#
A dict mapping between event names to their handlers
- class reactpy.core.types.EventHandlerFunc(*args, **kwargs)[source]#
Bases:
Protocol
A coroutine which can handle event data
- class reactpy.core.types.EventHandlerType(*args, **kwargs)[source]#
Bases:
Protocol
Defines a handler for some event
- function: EventHandlerFunc#
A coroutine which can respond to an event and its data
- target: str | None#
Typically left as
None
except when a static target is useful.When testing, it may be useful to specify a static target ID so events can be triggered programmatically.
Note
When
None
, it is left to aLayoutType
to auto generate a unique ID.
- class reactpy.core.types.VdomDictConstructor(*args, **kwargs)[source]#
Bases:
Protocol
Standard function for constructing a
VdomDict
- class reactpy.core.types.LayoutUpdateMessage(_typename, _fields=None, /, **kwargs)[source]#
Bases:
typing_extensions.TypedDict
A message describing an update to a layout
- type: Literal['layout-update']#
The type of message
- model: reactpy.core.types.VdomJson#
The model to assign at the given JSON Pointer path
- class reactpy.core.types.LayoutEventMessage(_typename, _fields=None, /, **kwargs)[source]#
Bases:
typing_extensions.TypedDict
Message describing an event originating from an element in the layout
- type: Literal['layout-event']#
The type of message
- data: collections.abc.Sequence[Any]#
A list of event data passed to the event handler.
- class reactpy.core.types.Context(*args, **kwargs)[source]#
Bases:
Protocol
[reactpy.core.types._Type
]Returns a
ContextProvider
component
- class reactpy.core.types.ContextProviderType(*args, **kwargs)[source]#
Bases:
reactpy.core.types.ComponentType
,Protocol
[reactpy.core.types._Type
]A component which provides a context value to its children
- property value: reactpy.core.types._Type#
Current context value
vdom
#
- reactpy.core.vdom.VDOM_JSON_SCHEMA = {'$ref': '#/definitions/element', '$schema': 'http://json-schema.org/draft-07/schema', 'definitions': {'element': {'dependentSchemas': {'error': {'properties': {'tagName': {'maxLength': 0}}}}, 'properties': {'attributes': {'type': 'object'}, 'children': {'$ref': '#/definitions/elementChildren'}, 'error': {'type': 'string'}, 'eventHandlers': {'$ref': '#/definitions/elementEventHandlers'}, 'importSource': {'$ref': '#/definitions/importSource'}, 'key': {'type': ['string', 'number', 'null']}, 'tagName': {'type': 'string'}}, 'required': ['tagName'], 'type': 'object'}, 'elementChildren': {'items': {'$ref': '#/definitions/elementOrString'}, 'type': 'array'}, 'elementEventHandlers': {'patternProperties': {'.*': {'$ref': '#/definitions/eventHandler'}}, 'type': 'object'}, 'elementOrString': {'if': {'type': 'object'}, 'then': {'$ref': '#/definitions/element'}, 'type': ['object', 'string']}, 'eventHandler': {'properties': {'preventDefault': {'type': 'boolean'}, 'stopPropagation': {'type': 'boolean'}, 'target': {'type': 'string'}}, 'required': ['target'], 'type': 'object'}, 'importSource': {'properties': {'fallback': {'if': {'not': {'type': 'null'}}, 'then': {'$ref': '#/definitions/elementOrString'}, 'type': ['object', 'string', 'null']}, 'source': {'type': 'string'}, 'sourceType': {'enum': ['URL', 'NAME']}, 'unmountBeforeUpdate': {'type': 'boolean'}}, 'required': ['source'], 'type': 'object'}}}#
JSON Schema describing serialized VDOM - see VDOM for more info
- reactpy.core.vdom.validate_vdom_json(value)[source]#
Validate serialized VDOM - see
VDOM_JSON_SCHEMA
for more info- Parameters
value (Any) β
- Return type
- reactpy.core.vdom.is_vdom(value)[source]#
Return whether a value is a
VdomDict
This employs a very simple heuristic - something is VDOM if:
It is a
dict
instanceIt contains the key
"tagName"
The value of the key
"tagName"
is a string
Note
Performing an
isinstance(value, VdomDict)
check is too restrictive since the user would be forced to importVdomDict
every time they needed to declare a VDOM element. Giving the user more flexibility, at the cost of this checkβs accuracy, is worth it.
- reactpy.core.vdom.vdom(tag: str, *children: VdomChildren) reactpy.core.types.VdomDict [source]#
- reactpy.core.vdom.vdom(tag: str, attributes: collections.abc.Mapping[str, Any], *children: VdomChildren) reactpy.core.types.VdomDict
A helper function for creating VDOM elements.
- Parameters
tag β The type of element (e.g. βdivβ, βh1β, βimgβ)
attributes_and_children β An optional attribute mapping followed by any number of children or iterables of children. The attribute mapping must precede the children, or children which will be merged into their respective parts of the model.
key β A string indicating the identity of a particular element. This is significant to preserve event handlers across updates - without a key, a re-render would cause these handlers to be deleted, but with a key, they would be redirected to any newly defined handlers.
event_handlers β Maps event types to coroutines that are responsible for handling those events.
import_source β (subject to change) specifies javascript that, when evaluated returns a React component.
- reactpy.core.vdom.make_vdom_constructor(tag, allow_children=True, import_source=None)[source]#
Return a constructor for VDOM dictionaries with the given tag name.
The resulting callable will have the same interface as
vdom()
but without its firsttag
argument.- Parameters
tag (str) β
allow_children (bool) β
import_source (ImportSourceDict | None) β
- Return type
testing
#
backend
#
- class reactpy.testing.backend.BackendFixture(host='127.0.0.1', port=None, app=None, implementation=None, options=None, timeout=None)[source]#
Bases:
object
A test fixture for running a server and imperatively displaying views
This fixture is typically used alongside async web drivers like
playwight
.Example
async with BackendFixture() as server: server.mount(MyComponent)
- Parameters
host (str) β
port (int | None) β
app (Any | None) β
implementation (BackendType[Any] | None) β
options (Any | None) β
timeout (float | None) β
- Return type
None
- property log_records: list[logging.LogRecord]#
A list of captured log records
common
#
- reactpy.testing.common.clear_reactpy_web_modules_dir()[source]#
Clear the directory where ReactPy stores registered web modules
- Return type
None
- class reactpy.testing.common.poll(function, *args, **kwargs)[source]#
Bases:
Generic
[reactpy.testing.common._R
]Wait until the result of an sync or async function meets some condition
- Parameters
function (Callable[_P, Awaitable[_R] | _R]) β
args (_P.args) β
kwargs (_P.kwargs) β
- Return type
None
- async until(condition, timeout=5.0, delay=0.1, description='condition to be true')[source]#
Check that the coroutines result meets a condition within the timeout
- class reactpy.testing.common.HookCatcher(index_by_kwarg=None)[source]#
Bases:
object
Utility for capturing a LifeCycleHook from a component
Example
hooks = HookCatcher(index_by_kwarg="thing") @reactpy.component @hooks.capture def MyComponent(thing): ... ... # render the component # grab the last render of where MyComponent(thing='something') hooks.index["something"] # or grab the hook from the component's last render hooks.latest
After the first render of
MyComponent
theHookCatcher
will have captured the componentβsLifeCycleHook
.- Parameters
index_by_kwarg (str | None) β
- class reactpy.testing.common.StaticEventHandler[source]#
Bases:
object
Utility for capturing the target of one event handler
Example
static_handler = StaticEventHandler() @reactpy.component def MyComponent(): state, set_state = reactpy.hooks.use_state(0) handler = static_handler.use(lambda event: set_state(state + 1)) return reactpy.html.button({"onClick": handler}, "Click me!") # gives the target ID for onClick where from the last render of MyComponent static_handlers.target
If you need to capture event handlers from different instances of a component the you should create multiple
StaticEventHandler
instances.static_handlers_by_key = { "first": StaticEventHandler(), "second": StaticEventHandler(), } @reactpy.component def Parent(): return reactpy.html.div(Child(key="first"), Child(key="second")) @reactpy.component def Child(key): state, set_state = reactpy.hooks.use_state(0) handler = static_handlers_by_key[key].use(lambda event: set_state(state + 1)) return reactpy.html.button({"onClick": handler}, "Click me!") # grab the individual targets for each instance above first_target = static_handlers_by_key["first"].target second_target = static_handlers_by_key["second"].target
- Return type
None
display
#
- class reactpy.testing.display.DisplayFixture(backend=None, driver=None, url_prefix='')[source]#
Bases:
object
A fixture for running web-based tests using
playwright
- Parameters
backend (BackendFixture | None) β
driver (Browser | BrowserContext | Page | None) β
url_prefix (str) β
- Return type
None
logs
#
- exception reactpy.testing.logs.LogAssertionError[source]#
Bases:
AssertionError
An assertion error raised in relation to log messages.
- reactpy.testing.logs.assert_reactpy_did_log(match_message='', error_type=None, match_error='')[source]#
Assert that ReactPy produced a log matching the described message or error.
- reactpy.testing.logs.assert_reactpy_did_not_log(match_message='', error_type=None, match_error='')[source]#
Assert the inverse of
assert_reactpy_logged()
- reactpy.testing.logs.list_logged_exceptions(log_records, pattern='', types=<class 'Exception'>, log_level=40, del_log_records=True)[source]#
Return a list of logged exception matching the given criteria
- Parameters
- Return type
web
#
module
#
- reactpy.web.module.NAME_SOURCE = 'NAME'#
A named source - usually a Javascript package name
- reactpy.web.module.URL_SOURCE = 'URL'#
A source loaded from a URL, usually a CDN
- reactpy.web.module.module_from_url(url, fallback=None, resolve_exports=None, resolve_exports_depth=5, unmount_before_update=False)[source]#
Load a
WebModule
from aURL_SOURCE
- Parameters
url (str) β Where the javascript module will be loaded from which conforms to the interface for Custom Javascript Components
fallback (Any | None) β What to temporarily display while the module is being loaded.
resolve_imports β Whether to try and find all the named exports of this module.
resolve_exports_depth (int) β How deeply to search for those exports.
unmount_before_update (bool) β Cause the component to be unmounted before each update. This option should only be used if the imported package fails to re-render when props change. Using this option has negative performance consequences since all DOM elements must be changed on each render. See #461 for more info.
resolve_exports (bool | None) β
- Return type
- reactpy.web.module.module_from_template(template, package, cdn='https://esm.sh', fallback=None, resolve_exports=None, resolve_exports_depth=5, unmount_before_update=False)[source]#
Create a
WebModule
from a framework templateThis is useful for experimenting with component libraries that do not already support ReactPyβs Custom Javascript Components interface.
Warning
This approach is not recommended for use in a production setting because the framework templates may use unpinned dependencies that could change without warning. Itβs best to author a module adhering to the Custom Javascript Components interface instead.
Templates
react
: for modules exporting React components
- Parameters
template (str) β The name of the framework template to use with the given
package
.package (str) β The name of a package to load. May include a file extension (defaults to
.js
if not given)cdn (str) β Where the package should be loaded from. The CDN must distribute ESM modules
fallback (Any | None) β What to temporarily display while the module is being loaded.
resolve_imports β Whether to try and find all the named exports of this module.
resolve_exports_depth (int) β How deeply to search for those exports.
unmount_before_update (bool) β Cause the component to be unmounted before each update. This option should only be used if the imported package fails to re-render when props change. Using this option has negative performance consequences since all DOM elements must be changed on each render. See #461 for more info.
resolve_exports (bool | None) β
- Return type
- reactpy.web.module.module_from_file(name, file, fallback=None, resolve_exports=None, resolve_exports_depth=5, unmount_before_update=False, symlink=False)[source]#
Load a
WebModule
from a givenfile
- Parameters
name (str) β The name of the package
file (str | Path) β The file from which the content of the web module will be created.
fallback (Any | None) β What to temporarily display while the module is being loaded.
resolve_imports β Whether to try and find all the named exports of this module.
resolve_exports_depth (int) β How deeply to search for those exports.
unmount_before_update (bool) β Cause the component to be unmounted before each update. This option should only be used if the imported package fails to re-render when props change. Using this option has negative performance consequences since all DOM elements must be changed on each render. See #461 for more info.
symlink (bool) β Whether the web module should be saved as a symlink to the given
file
.resolve_exports (bool | None) β
- Return type
- reactpy.web.module.module_from_string(name, content, fallback=None, resolve_exports=None, resolve_exports_depth=5, unmount_before_update=False)[source]#
Load a
WebModule
whosecontent
comes from a string.- Parameters
name (str) β The name of the package
content (str) β The contents of the web module
fallback (Any | None) β What to temporarily display while the module is being loaded.
resolve_imports β Whether to try and find all the named exports of this module.
resolve_exports_depth (int) β How deeply to search for those exports.
unmount_before_update (bool) β Cause the component to be unmounted before each update. This option should only be used if the imported package fails to re-render when props change. Using this option has negative performance consequences since all DOM elements must be changed on each render. See #461 for more info.
resolve_exports (bool | None) β
- Return type
- class reactpy.web.module.WebModule(source: 'str', source_type: 'SourceType', default_fallback: 'Any | None', export_names: 'set[str] | None', file: 'Path | None', unmount_before_update: 'bool')[source]#
Bases:
object
- reactpy.web.module.export(web_module: reactpy.web.module.WebModule, export_names: str, fallback: Any | None = None, allow_children: bool = True) reactpy.core.types.VdomDictConstructor [source]#
- reactpy.web.module.export(web_module: reactpy.web.module.WebModule, export_names: list[str] | tuple[str, ...], fallback: Any | None = None, allow_children: bool = True) list[reactpy.core.types.VdomDictConstructor]
Return one or more VDOM constructors from a
WebModule
- Parameters
export_names β One or more names to export. If given as a string, a single component will be returned. If a list is given, then a list of components will be returned.
fallback β What to temporarily display while the module is being loaded.
allow_children β Whether or not these components can have children.
utils
#
__main__
#
_option
#
- class reactpy._option.Option(name, default=<object object>, mutable=True, parent=None, validator=<function Option.<lambda>>)[source]#
Bases:
Generic
[reactpy._option._O
]An option that can be set using an environment variable of the same name
- Parameters
- Return type
None
- property default: reactpy._option._O#
This optionβs default value
- set_current(new)[source]#
Set the value of this option
Raises a
TypeError
if this option is notOption.mutable
.- Parameters
new (Any) β
- Return type
None
- set_default(new)[source]#
Set the value of this option if not
Option.is_set()
Returns the current value (a la
dict.set_default()
)- Parameters
new (reactpy._option._O) β
- Return type
reactpy._option._O
- class reactpy._option.DeprecatedOption(*args, message, **kwargs)[source]#
Bases:
reactpy._option.Option
[reactpy._option._O
]An option that will warn when it is accessed
- Parameters
args (Any) β
message (str) β
kwargs (Any) β
- Return type
None
_warnings
#
config
#
ReactPy provides a series of configuration options that can be set using environment variables or, for those which allow it, a programmatic interface.
- reactpy.config.REACTPY_DEBUG_MODE = Option(REACTPY_DEBUG_MODE=False)#
Get extra logs and validation checks at the cost of performance.
This will enable the following:
- reactpy.config.REACTPY_CHECK_VDOM_SPEC = Option(REACTPY_CHECK_VDOM_SPEC=False)#
Checks which ensure VDOM is rendered to spec
For more info on the VDOM spec, see here: VDOM JSON Schema
- reactpy.config.REACTPY_CHECK_JSON_ATTRS = Option(REACTPY_CHECK_JSON_ATTRS=False)#
Checks that all VDOM attributes are JSON serializable
The VDOM spec is not able to enforce this on its own since attributes could anything.
- reactpy.config.REACTPY_WEB_MODULES_DIR = Option(REACTPY_WEB_MODULES_DIR=PosixPath('/tmp/tmpci6en0iq'))#
The location ReactPy will use to store its client application
This directory MUST be treated as a black box. Downstream applications MUST NOT assume anything about the structure of this directory see
reactpy.web.module
for a set of publicly available APIs for working with the client.
- reactpy.config.REACTPY_TESTING_DEFAULT_TIMEOUT = Option(REACTPY_TESTING_DEFAULT_TIMEOUT=5.0)#
A default timeout for testing utilities in ReactPy
- reactpy.config.REACTPY_ASYNC_RENDERING = Option(REACTPY_ASYNC_RENDERING=False)#
Whether to render components asynchronously. This is currently an experimental feature.
future
#
html
#
Fragment
Document metadata
Content sectioning
Text content
Inline text semantics
Image and video
Embedded content
SVG and MathML
Scripting
Demarcating edits
Table content
Forms
Interactive elements
Web components
- reactpy.html._(attributes, children, key, event_handlers)#
An HTML fragment - this element will not appear in the DOM
- Parameters
attributes (VdomAttributes) β
children (Sequence[VdomChild]) β
key (Key | None) β
event_handlers (EventHandlerDict) β
- Return type
- reactpy.html.base(*attributes_and_children, **kwargs)#
Return a new <base> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.head(*attributes_and_children, **kwargs)#
Return a new <head> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.link(*attributes_and_children, **kwargs)#
Return a new <link> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.meta(*attributes_and_children, **kwargs)#
Return a new <meta> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.style(*attributes_and_children, **kwargs)#
Return a new <style> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.title(*attributes_and_children, **kwargs)#
Return a new <title> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.address(*attributes_and_children, **kwargs)#
Return a new <address> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.article(*attributes_and_children, **kwargs)#
Return a new <article> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.aside(*attributes_and_children, **kwargs)#
Return a new <aside> element represented by a
VdomDict
.- Parameters
- Return type
Return a new <footer> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.header(*attributes_and_children, **kwargs)#
Return a new <header> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.h1(*attributes_and_children, **kwargs)#
Return a new <h1> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.h2(*attributes_and_children, **kwargs)#
Return a new <h2> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.h3(*attributes_and_children, **kwargs)#
Return a new <h3> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.h4(*attributes_and_children, **kwargs)#
Return a new <h4> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.h5(*attributes_and_children, **kwargs)#
Return a new <h5> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.h6(*attributes_and_children, **kwargs)#
Return a new <h6> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.main(*attributes_and_children, **kwargs)#
Return a new <main> element represented by a
VdomDict
.- Parameters
- Return type
Return a new <nav> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.section(*attributes_and_children, **kwargs)#
Return a new <section> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.blockquote(*attributes_and_children, **kwargs)#
Return a new <blockquote> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.dd(*attributes_and_children, **kwargs)#
Return a new <dd> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.div(*attributes_and_children, **kwargs)#
Return a new <div> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.dl(*attributes_and_children, **kwargs)#
Return a new <dl> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.dt(*attributes_and_children, **kwargs)#
Return a new <dt> element represented by a
VdomDict
.- Parameters
- Return type
Return a new <figcaption> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.figure(*attributes_and_children, **kwargs)#
Return a new <figure> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.hr(*attributes_and_children, **kwargs)#
Return a new <hr> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.li(*attributes_and_children, **kwargs)#
Return a new <li> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.ol(*attributes_and_children, **kwargs)#
Return a new <ol> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.p(*attributes_and_children, **kwargs)#
Return a new <p> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.pre(*attributes_and_children, **kwargs)#
Return a new <pre> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.ul(*attributes_and_children, **kwargs)#
Return a new <ul> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.a(*attributes_and_children, **kwargs)#
Return a new <a> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.abbr(*attributes_and_children, **kwargs)#
Return a new <abbr> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.b(*attributes_and_children, **kwargs)#
Return a new <b> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.bdi(*attributes_and_children, **kwargs)#
Return a new <bdi> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.bdo(*attributes_and_children, **kwargs)#
Return a new <bdo> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.br(*attributes_and_children, **kwargs)#
Return a new <br> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.cite(*attributes_and_children, **kwargs)#
Return a new <cite> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.code(*attributes_and_children, **kwargs)#
Return a new <code> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.data(*attributes_and_children, **kwargs)#
Return a new <data> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.em(*attributes_and_children, **kwargs)#
Return a new <em> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.i(*attributes_and_children, **kwargs)#
Return a new <i> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.kbd(*attributes_and_children, **kwargs)#
Return a new <kbd> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.mark(*attributes_and_children, **kwargs)#
Return a new <mark> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.q(*attributes_and_children, **kwargs)#
Return a new <q> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.rp(*attributes_and_children, **kwargs)#
Return a new <rp> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.rt(*attributes_and_children, **kwargs)#
Return a new <rt> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.ruby(*attributes_and_children, **kwargs)#
Return a new <ruby> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.s(*attributes_and_children, **kwargs)#
Return a new <s> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.samp(*attributes_and_children, **kwargs)#
Return a new <samp> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.small(*attributes_and_children, **kwargs)#
Return a new <small> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.span(*attributes_and_children, **kwargs)#
Return a new <span> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.strong(*attributes_and_children, **kwargs)#
Return a new <strong> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.sub(*attributes_and_children, **kwargs)#
Return a new <sub> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.sup(*attributes_and_children, **kwargs)#
Return a new <sup> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.time(*attributes_and_children, **kwargs)#
Return a new <time> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.u(*attributes_and_children, **kwargs)#
Return a new <u> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.var(*attributes_and_children, **kwargs)#
Return a new <var> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.wbr(*attributes_and_children, **kwargs)#
Return a new <wbr> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.area(*attributes_and_children, **kwargs)#
Return a new <area> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.audio(*attributes_and_children, **kwargs)#
Return a new <audio> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.img(*attributes_and_children, **kwargs)#
Return a new <img> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.map(*attributes_and_children, **kwargs)#
Return a new <map> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.track(*attributes_and_children, **kwargs)#
Return a new <track> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.video(*attributes_and_children, **kwargs)#
Return a new <video> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.embed(*attributes_and_children, **kwargs)#
Return a new <embed> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.iframe(*attributes_and_children, **kwargs)#
Return a new <iframe> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.object(*attributes_and_children, **kwargs)#
Return a new <object> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.param(*attributes_and_children, **kwargs)#
Return a new <param> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.picture(*attributes_and_children, **kwargs)#
Return a new <picture> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.portal(*attributes_and_children, **kwargs)#
Return a new <portal> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.source(*attributes_and_children, **kwargs)#
Return a new <source> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.svg(*attributes_and_children, **kwargs)#
Return a new <svg> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.math(*attributes_and_children, **kwargs)#
Return a new <math> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.canvas(*attributes_and_children, **kwargs)#
Return a new <canvas> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.noscript(*attributes_and_children, **kwargs)#
Return a new <noscript> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.script(attributes, children, key, event_handlers)#
Create a new <script> element.
Warning
Be careful to sanitize data from untrusted sources before using it in a script. See the βNotesβ for more details
This behaves slightly differently than a normal script element in that it may be run multiple times if its key changes (depending on specific browser behaviors). If no key is given, the key is inferred to be the content of the script or, lastly its βsrcβ attribute if that is given.
If no attributes are given, the content of the script may evaluate to a function. This function will be called when the script is initially created or when the content of the script changes. The function may itself optionally return a teardown function that is called when the script element is removed from the tree, or when the script content changes.
Notes
Do not use unsanitized data from untrusted sources anywhere in your script. Doing so may allow for malicious code injection. Consider this insecure code:
my_script = html.script(f"console.log('{user_bio}');")
A clever attacker could construct
user_bio
such that they could escape the string and execute arbitrary code to perform cross-site scripting (XSS <https://en.wikipedia.org/wiki/Cross-site_scripting>`__). For example, what ifuser_bio
were of the form:'); attackerCodeHere(); ('
This would allow the following Javascript code to be executed client-side:
console.log(''); attackerCodeHere(); ('');
One way to avoid this could be to escape
user_bio
so as to prevent the injection of Javascript code. For example:import json my_script = html.script(f"console.log({json.dumps(user_bio)});")
This would prevent the injection of Javascript code by escaping the
user_bio
string. In this case, the following client-side code would be executed instead:console.log("'); attackerCodeHere(); ('");
This is a very simple example, but it illustrates the point that you should always be careful when using unsanitized data from untrusted sources.
- Parameters
attributes (VdomAttributes) β
children (Sequence[VdomChild]) β
key (Key | None) β
event_handlers (EventHandlerDict) β
- Return type
- reactpy.html.del_(*attributes_and_children, **kwargs)#
Return a new <del> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.ins(*attributes_and_children, **kwargs)#
Return a new <ins> element represented by a
VdomDict
.- Parameters
- Return type
Return a new <caption> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.col(*attributes_and_children, **kwargs)#
Return a new <col> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.colgroup(*attributes_and_children, **kwargs)#
Return a new <colgroup> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.table(*attributes_and_children, **kwargs)#
Return a new <table> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.tbody(*attributes_and_children, **kwargs)#
Return a new <tbody> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.td(*attributes_and_children, **kwargs)#
Return a new <td> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.tfoot(*attributes_and_children, **kwargs)#
Return a new <tfoot> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.th(*attributes_and_children, **kwargs)#
Return a new <th> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.thead(*attributes_and_children, **kwargs)#
Return a new <thead> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.tr(*attributes_and_children, **kwargs)#
Return a new <tr> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.button(*attributes_and_children, **kwargs)#
Return a new <button> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.fieldset(*attributes_and_children, **kwargs)#
Return a new <fieldset> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.form(*attributes_and_children, **kwargs)#
Return a new <form> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.input(*attributes_and_children, **kwargs)#
Return a new <input> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.label(*attributes_and_children, **kwargs)#
Return a new <label> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.legend(*attributes_and_children, **kwargs)#
Return a new <legend> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.meter(*attributes_and_children, **kwargs)#
Return a new <meter> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.option(*attributes_and_children, **kwargs)#
Return a new <option> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.output(*attributes_and_children, **kwargs)#
Return a new <output> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.progress(*attributes_and_children, **kwargs)#
Return a new <progress> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.select(*attributes_and_children, **kwargs)#
Return a new <select> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.textarea(*attributes_and_children, **kwargs)#
Return a new <textarea> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.details(*attributes_and_children, **kwargs)#
Return a new <details> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.dialog(*attributes_and_children, **kwargs)#
Return a new <dialog> element represented by a
VdomDict
.- Parameters
- Return type
Return a new <menu> element represented by a
VdomDict
.- Parameters
- Return type
Return a new <menuitem> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.summary(*attributes_and_children, **kwargs)#
Return a new <summary> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.slot(*attributes_and_children, **kwargs)#
Return a new <slot> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.html.template(*attributes_and_children, **kwargs)#
Return a new <template> element represented by a
VdomDict
.- Parameters
- Return type
logging
#
- reactpy.logging.ROOT_LOGGER = <Logger reactpy (INFO)>#
ReactPyβs root logger instance
sample
#
svg
#
- reactpy.svg.a(*attributes_and_children, **kwargs)#
Return a new <a> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.animate(*attributes_and_children, **kwargs)#
Return a new <animate> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.animate_motion(*attributes_and_children, **kwargs)#
Return a new <animateMotion> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.animate_transform(*attributes_and_children, **kwargs)#
Return a new <animateTransform> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.circle(*attributes_and_children, **kwargs)#
Return a new <circle> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.clip_path(*attributes_and_children, **kwargs)#
Return a new <clipPath> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.defs(*attributes_and_children, **kwargs)#
Return a new <defs> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.desc(*attributes_and_children, **kwargs)#
Return a new <desc> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.discard(*attributes_and_children, **kwargs)#
Return a new <discard> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.ellipse(*attributes_and_children, **kwargs)#
Return a new <ellipse> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_blend(*attributes_and_children, **kwargs)#
Return a new <feBlend> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_color_matrix(*attributes_and_children, **kwargs)#
Return a new <feColorMatrix> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_component_transfer(*attributes_and_children, **kwargs)#
Return a new <feComponentTransfer> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_composite(*attributes_and_children, **kwargs)#
Return a new <feComposite> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_convolve_matrix(*attributes_and_children, **kwargs)#
Return a new <feConvolveMatrix> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_diffuse_lighting(*attributes_and_children, **kwargs)#
Return a new <feDiffuseLighting> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_displacement_map(*attributes_and_children, **kwargs)#
Return a new <feDisplacementMap> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_distant_light(*attributes_and_children, **kwargs)#
Return a new <feDistantLight> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_drop_shadow(*attributes_and_children, **kwargs)#
Return a new <feDropShadow> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_flood(*attributes_and_children, **kwargs)#
Return a new <feFlood> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_func_a(*attributes_and_children, **kwargs)#
Return a new <feFuncA> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_func_b(*attributes_and_children, **kwargs)#
Return a new <feFuncB> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_func_g(*attributes_and_children, **kwargs)#
Return a new <feFuncG> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_func_r(*attributes_and_children, **kwargs)#
Return a new <feFuncR> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_gaussian_blur(*attributes_and_children, **kwargs)#
Return a new <feGaussianBlur> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_image(*attributes_and_children, **kwargs)#
Return a new <feImage> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_merge(*attributes_and_children, **kwargs)#
Return a new <feMerge> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_merge_node(*attributes_and_children, **kwargs)#
Return a new <feMergeNode> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_morphology(*attributes_and_children, **kwargs)#
Return a new <feMorphology> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_offset(*attributes_and_children, **kwargs)#
Return a new <feOffset> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_point_light(*attributes_and_children, **kwargs)#
Return a new <fePointLight> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_specular_lighting(*attributes_and_children, **kwargs)#
Return a new <feSpecularLighting> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_spot_light(*attributes_and_children, **kwargs)#
Return a new <feSpotLight> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_tile(*attributes_and_children, **kwargs)#
Return a new <feTile> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.fe_turbulence(*attributes_and_children, **kwargs)#
Return a new <feTurbulence> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.filter(*attributes_and_children, **kwargs)#
Return a new <filter> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.foreign_object(*attributes_and_children, **kwargs)#
Return a new <foreignObject> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.g(*attributes_and_children, **kwargs)#
Return a new <g> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.hatch(*attributes_and_children, **kwargs)#
Return a new <hatch> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.hatchpath(*attributes_and_children, **kwargs)#
Return a new <hatchpath> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.image(*attributes_and_children, **kwargs)#
Return a new <image> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.line(*attributes_and_children, **kwargs)#
Return a new <line> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.linear_gradient(*attributes_and_children, **kwargs)#
Return a new <linearGradient> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.marker(*attributes_and_children, **kwargs)#
Return a new <marker> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.mask(*attributes_and_children, **kwargs)#
Return a new <mask> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.metadata(*attributes_and_children, **kwargs)#
Return a new <metadata> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.mpath(*attributes_and_children, **kwargs)#
Return a new <mpath> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.path(*attributes_and_children, **kwargs)#
Return a new <path> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.pattern(*attributes_and_children, **kwargs)#
Return a new <pattern> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.polygon(*attributes_and_children, **kwargs)#
Return a new <polygon> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.polyline(*attributes_and_children, **kwargs)#
Return a new <polyline> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.radial_gradient(*attributes_and_children, **kwargs)#
Return a new <radialGradient> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.rect(*attributes_and_children, **kwargs)#
Return a new <rect> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.script(*attributes_and_children, **kwargs)#
Return a new <script> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.set(*attributes_and_children, **kwargs)#
Return a new <set> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.stop(*attributes_and_children, **kwargs)#
Return a new <stop> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.style(*attributes_and_children, **kwargs)#
Return a new <style> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.svg(*attributes_and_children, **kwargs)#
Return a new <svg> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.switch(*attributes_and_children, **kwargs)#
Return a new <switch> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.symbol(*attributes_and_children, **kwargs)#
Return a new <symbol> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.text(*attributes_and_children, **kwargs)#
Return a new <text> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.text_path(*attributes_and_children, **kwargs)#
Return a new <textPath> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.title(*attributes_and_children, **kwargs)#
Return a new <title> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.tspan(*attributes_and_children, **kwargs)#
Return a new <tspan> element represented by a
VdomDict
.- Parameters
- Return type
- reactpy.svg.use(*attributes_and_children, **kwargs)#
Return a new <use> element represented by a
VdomDict
.- Parameters
- Return type
types
#
Exports common types from:
utils
#
- class reactpy.utils.Ref(initial_value=<object object>)[source]#
Bases:
Generic
[reactpy.utils._RefValue
]Hold a reference to a value
This is used in imperative code to mutate the state of this object in order to incur side effects. Generally refs should be avoided if possible, but sometimes they are required.
Notes
You can compare the contents for two
Ref
objects using the==
operator.- Parameters
initial_value (_RefValue) β
- Return type
None
- current#
The present value
- reactpy.utils.vdom_to_html(vdom)[source]#
Convert a VDOM dictionary into an HTML string
Only the following keys are translated to HTML:
tagName
attributes
children
(must be strings or more VDOM dicts)
- Parameters
vdom (reactpy.core.types.VdomDict) β The VdomDict element to convert to HTML
- Return type
- reactpy.utils.html_to_vdom(html, *transforms, strict=True)[source]#
Transform HTML into a DOM model. Unique keys can be provided to HTML elements using a
key=...
attribute within your HTML tag.- Parameters
html (str) β The raw HTML as a string
transforms (Callable[[reactpy.core.types.VdomDict], Any]) β Functions of the form
transform(old) -> new
whereold
is a VDOM dictionary which will be replaced bynew
. For example, you could use a transform function to add highlighting to a<code/>
block.strict (bool) β If
True
, raise an exception if the HTML does not perfectly follow HTML5 syntax.
- Return type
- exception reactpy.utils.HTMLParseError[source]#
Bases:
lxml.etree.LxmlSyntaxError
Raised when an HTML document cannot be parsed using strict parsing.
- reactpy.utils.del_html_head_body_transform(vdom)[source]#
Transform intended for use with html_to_vdom.
Removes <html>, <head>, and <body> while preserving their children.
- Parameters
vdom (reactpy.core.types.VdomDict) β The VDOM dictionary to transform.
- Return type
widgets
#
- reactpy.widgets.image(format, value='', attributes=None)[source]#
Utility for constructing an image from a string or bytes
The source value will automatically be encoded to base64
- reactpy.widgets.use_linked_inputs(attributes, on_change=<function <lambda>>, cast=<function <lambda>>, initial_value='', ignore_empty=True)[source]#
Return a list of linked inputs equal to the number of given attributes.
- Parameters
attributes (collections.abc.Sequence[dict[str, Any]]) β That attributes of each returned input element. If the number of generated inputs is variable, you may need to assign each one a key by including a
"key"
in each attribute dictionary.on_change (Callable[[reactpy.widgets._Value], None]) β A callback which is triggered when any input is changed. This callback need not update the βvalueβ field in the attributes of the inputs since that is handled automatically.
cast (reactpy.widgets._CastFunc[reactpy.widgets._Value]) β Cast the βvalueβ of changed inputs that is passed to
on_change
.initial_value (str) β Initialize the βvalueβ field of the inputs.
ignore_empty (bool) β Do not trigger
on_change
if the βvalueβ is an empty string.
- Return type