pytauri.ipc
¶
Classes:
| Name | Description |
|---|---|
ArgumentsType |
The bound arguments of a command. |
Invoke |
|
InvokeResolver |
|
ParametersType |
The parameters of a command. |
ResolvedArgumentsType |
The resolved arguments of a invoked command. |
State |
A marker for state in ArgumentsType. |
InvokeException |
Indicates that an exception occurred in a |
Commands |
This class provides features similar to tauri::generate_handler. |
JavaScriptChannelId |
This class is a wrapper around pytauri.ffi.ipc.JavaScriptChannelId. |
Channel |
This class is a wrapper around pytauri.ffi.ipc.Channel. |
Attributes:
| Name | Type | Description |
|---|---|---|
Headers |
Headers
module-attribute
¶
Headers = TypeAliasType('Headers', list[tuple[bytes, bytes]])
(key, value) pairs of headers.
Each key will be yielded once per associated value. So, if a key has 3 associated values, it will be yielded 3 times.
Tip
You can use libraries like multidict or httpx.Headers to convert it into dict for more efficient retrieval of a specific header.
__all__
module-attribute
¶
__all__ = ['ArgumentsType', 'Channel', 'Commands', 'Headers', 'Invoke', 'InvokeException', 'InvokeResolver', 'JavaScriptChannelId', 'ParametersType', 'ResolvedArgumentsType', 'State']
ArgumentsType
¶
Bases: _BaseArgumentsType
The bound arguments of a command.
Each key is optional, depending on the keys of the bound ResolvedArgumentsType.
You can use it like **kwargs, for example command(**arguments).
Attributes:
| Name | Type | Description |
|---|---|---|
body |
bytes
|
The body of this ipc message. |
app_handle |
AppHandle
|
The handle of the app. |
webview_window |
WebviewWindow
|
The |
headers |
Headers
|
The headers of this ipc message. |
Invoke
¶
Methods:
| Name | Description |
|---|---|
bind_to |
Consumes this |
resolve |
Consumes this |
reject |
Consumes this |
Attributes:
| Name | Type | Description |
|---|---|---|
command |
str
|
The name of the current command. |
bind_to
¶
bind_to(parameters: ParametersType) -> Optional[InvokeResolver[_ArgumentsTypeVar]]
Consumes this Invoke and binds parameters.
If the frontend illegally calls the IPC,
this method will automatically reject this Invoke and return None.
The return value InvokeResolver.arguments
is not the same object as the input parameters.
Source code in python/pytauri/src/pytauri/ffi/ipc.py
resolve
¶
resolve(value: _InvokeResponseBody) -> None
Consumes this Invoke and resolves the command with the given value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
_InvokeResponseBody
|
The value to resolve the command with.
|
required |
Source code in python/pytauri/src/pytauri/ffi/ipc.py
InvokeResolver
¶
Bases: Generic[_ArgumentsTypeVar]
Methods:
| Name | Description |
|---|---|
resolve |
Consumes this |
reject |
Consumes this |
Attributes:
| Name | Type | Description |
|---|---|---|
arguments |
_ArgumentsTypeVar
|
The bound arguments of the current command. |
resolve
¶
resolve(value: _InvokeResponseBody) -> None
Consumes this InvokeResolver and resolves the command with the given value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
_InvokeResponseBody
|
The value to resolve the command with.
|
required |
Source code in python/pytauri/src/pytauri/ffi/ipc.py
ParametersType
¶
Bases: TypedDict
The parameters of a command.
You can use this with Invoke.bind_to. All keys are optional. If a key exists, it will be assigned a value corresponding to ResolvedArgumentsType.
Attributes:
| Name | Type | Description |
|---|---|---|
body |
Any
|
Whatever. We just use the |
app_handle |
Any
|
Whatever. We just use the |
webview_window |
Any
|
Whatever. We just use the |
headers |
Any
|
Whatever. We just use the |
states |
dict[str, type[Any]]
|
A dictionary of state classes. |
ResolvedArgumentsType
¶
Bases: _BaseArgumentsType
The resolved arguments of a invoked command.
It contains the resolved values of the parameters in ParametersType.
Attributes:
| Name | Type | Description |
|---|---|---|
body |
bytes
|
The body of this ipc message. |
app_handle |
AppHandle
|
The handle of the app. |
webview_window |
WebviewWindow
|
The |
headers |
Headers
|
The headers of this ipc message. |
states |
dict[str, Any]
|
The value is an instance of the state class in ParametersType.states. |
states
instance-attribute
¶
The value is an instance of the state class in ParametersType.states.
State
¶
A marker for state in ArgumentsType.
Examples¶
InvokeException
¶
InvokeException(value: str)
Bases: Exception
Indicates that an exception occurred in a command. Similar to Rust's Result::Err.
When this exception is raised in a command,
pytauri will return it to the frontend through Invoke.reject(value)
and will not log the exception on the python side.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
str
|
The error message that will be returned to the frontend. |
Source code in python/pytauri/src/pytauri/ipc.py
Commands
¶
Commands(*, experimental_gen_ts: bool = False)
Bases: UserDict[str, _PyInvokHandleData]
This class provides features similar to tauri::generate_handler.
Typically, you would use Commands.command to register a command handler function.
Then, use Commands.generate_handler to get an invoke_handler
for use with BuilderArgs.
Methods:
| Name | Description |
|---|---|
generate_handler |
This method is similar to tauri::generate_handler. |
wrap_pyfunc |
Wrap a |
parse_parameters |
Check the signature of a |
set_command |
Set a command handler. |
command |
A decorator to register a command handler. |
experimental_gen_ts |
Generate TypeScript types and API client from the registered commands. |
experimental_gen_ts_background |
Generate TypeScript types and API client from the registered commands in the background. |
Source code in python/pytauri/src/pytauri/ipc.py
generate_handler
¶
generate_handler(portal: BlockingPortal) -> _InvokeHandlerProto
This method is similar to tauri::generate_handler.
You can use this method to get invoke_handler for use with BuilderArgs.
Examples:
from anyio.from_thread import start_blocking_portal
commands = Commands()
with start_blocking_portal(backend) as portal:
invoke_handler = commands.generate_handler(portal)
...
Warning
The portal must remain valid while the returned invoke_handler is being used.
Source code in python/pytauri/src/pytauri/ipc.py
wrap_pyfunc
¶
wrap_pyfunc(pyfunc: _WrappablePyHandlerType, *, _gen_ts_cmd: Optional[str] = None) -> _PyHandlerType
Wrap a Callable to conform to the definition of PyHandlerType.
Specifically:
- If
pyfunchas aKEYWORD_ONLYparameter namedbody:- If
bodyisbytes: do nothing. - If
issubclass(body, BaseModel): wrap this callable as a new function with abody: bytesparameter. - Otherwise:
try to convert it to a
BaseModel/TypeAdapter, and proceed as in theBaseModelbranch.
- If
- Handle the return type:
- If the return type is
bytes: do nothing. - If
issubclass(return_type, BaseModel): wrap this callable as a new function withreturn: strvalue. - Otherwise:
try to convert it to a
BaseModel/TypeAdapter, and proceed as in theBaseModelbranch.
- If the return type is
- If no wrapping is needed, the original
pyfuncwill be returned.
The pyfunc will be decorated using functools.wraps, and its __signature__ will also be updated.
Source code in python/pytauri/src/pytauri/ipc.py
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | |
parse_parameters
staticmethod
¶
parse_parameters(pyfunc: _PyHandlerType) -> ParametersType
Check the signature of a Callable and return the parameters.
Check if the Signature of pyfunc conforms to ArgumentsType,
and if the return value is bytes or str.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
_PyHandlerType
|
The |
required |
Returns:
| Type | Description |
|---|---|
ParametersType
|
The parameters of the |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the signature does not conform to the expected pattern. |
Source code in python/pytauri/src/pytauri/ipc.py
set_command
¶
set_command(command: str, handler: _WrappablePyHandlerType) -> None
Set a command handler.
This method internally calls parse_parameters
and wrap_pyfunc, parse_parameters(wrap_pyfunc(handler)).
Source code in python/pytauri/src/pytauri/ipc.py
command
¶
A decorator to register a command handler.
Examples:
commands = Commands()
@commands.command()
async def my_command(body: FooModel, app_handle: AppHandle) -> BarModel: ...
@commands.command("foo_command")
async def my_command2(
body: FooModel, app_handle: AppHandle
) -> BarModel: ...
This method internally calls set_command, which means the function signature must conform to ArgumentsType.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Optional[str]
|
The name of the command. If not provided, the |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a command with the same name already exists. If it's expected, use set_command instead. |
Source code in python/pytauri/src/pytauri/ipc.py
experimental_gen_ts
async
¶
experimental_gen_ts(output_dir: Union[str, PathLike[str]], json2ts_cmd: str, *, cmd_alias: Optional[Callable[[str], str]] = to_camel) -> None
Generate TypeScript types and API client from the registered commands.
This method is only available if experimental_gen_ts is set to True
when creating the Commands instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Union[str, PathLike[str]]
|
The directory to output the generated TypeScript files. |
required |
|
str
|
The command to run json-schema-to-typescript to generate TypeScript types. |
required |
|
Optional[Callable[[str], str]]
|
An optional function to convert command names to TypeScript style. By default, it uses to_camel. |
to_camel
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in python/pytauri/src/pytauri/ipc.py
experimental_gen_ts_background
async
¶
experimental_gen_ts_background(output_dir: Union[str, PathLike[str]], json2ts_cmd: str, *, cmd_alias: Optional[Callable[[str], str]] = to_camel) -> None
Generate TypeScript types and API client from the registered commands in the background.
See experimental_gen_ts for more details. This method is equivalent to:
try:
await self.experimental_gen_ts(
output_dir,
json2ts_cmd,
cmd_alias=cmd_alias,
)
except Exception:
logging.exception(...)
return None
Source code in python/pytauri/src/pytauri/ipc.py
JavaScriptChannelId
¶
Bases: RootModel[_FFIJavaScriptChannelIdAnno], Generic[_ModelTypeVar]
This class is a wrapper around pytauri.ffi.ipc.JavaScriptChannelId.
You can use this class as model field in pydantic model directly, or use it as model directly.
pytauri.ffi.ipc.JavaScriptChannelId can't be used directly in pydantic model.
Examples¶
from asyncio import Task, create_task, sleep
from typing import Any
from pydantic import BaseModel, RootModel
from pydantic.networks import HttpUrl
from pytauri import Commands
from pytauri.ipc import JavaScriptChannelId, WebviewWindow
commands = Commands()
Progress = RootModel[int]
class Download(BaseModel):
url: HttpUrl
channel: JavaScriptChannelId[Progress]
background_tasks: set[Task[Any]] = set()
@commands.command()
async def download(body: Download, webview_window: WebviewWindow) -> None:
channel = body.channel.channel_on(webview_window.as_ref_webview())
async def task():
progress = Progress(0)
while progress.root <= 100:
channel.send_model(progress)
await sleep(0.1)
progress.root += 1
t = create_task(task())
background_tasks.add(t)
t.add_done_callback(background_tasks.discard)
# Or you can use it as `body` model directly
@commands.command()
async def my_command(body: JavaScriptChannelId) -> bytes: ...
Methods:
| Name | Description |
|---|---|
from_str |
|
channel_on |
Channel
¶
Channel(ffi_channel: Channel)
Bases: Generic[_ModelTypeVar]
This class is a wrapper around pytauri.ffi.ipc.Channel.
It adds the following methods:
Examples¶
Methods:
| Name | Description |
|---|---|
id |
|
send |
|
send_model |
Equivalent to |