API πο
Controllerο
- pywebchannel.Controller.Action(notify: Notify = None)[source]ο
A decorator that converts a Python function into a Qt slot. The notify argument is used to emit after the function is executed. Defaults to None. If it is specified, a signal with the given name will be created and attached into the class. You donβt need to create that signal yourself. The signal will be emitted with the result of the function. EmitBy is used to specify the source of the notification. If it is set to EmitBy.Auto, the notification will be emitted automatically after the function is executed. If it is set to EmitBy.User, the notification will be emitted only if the function explicitly emits it.
- Parameters:
notify (Notify, optional) β A Notify object that specifies the name and arguments of a notification signal
- Returns:
A wrapper function that is a Qt slot with the same arguments and return type as the original function. The slot also handles serialization and deserialization of inputs and outputs, exception handling,and optionally emits a notification signal with the result.
References
https://doc.qt.io/qtforpython-6/tutorials/basictutorial/signals_and_slots.html
See also
Signal, Property
- class pywebchannel.Controller.Controller(controllerName: str, parent: QObject | None = None)[source]ο
Bases:
QObject
A base class for controllers that provides common functionality.
- _controllerNameο
A private instance attribute that stores the name of the controller.
- cleanup() None [source]ο
Performs any necessary cleanup actions before the controller is destroyed.
This method can be overridden by subclasses to implement their own cleanup logic.
- name() str [source]ο
Returns the name of the controller.
- Returns:
A string that represents the name of the controller.
- staticMetaObject = PySide6.QtCore.QMetaObject("Controller" inherits "QObject": )ο
- class pywebchannel.Controller.Convert[source]ο
Bases:
object
This class provides some utility methods to convert data types between Python, Qt, and web formats.
- static from_py_to_qt(argDict: Dict[str, type]) Tuple[List[str], List[type]] [source]ο
- Converts a dictionary of argument names and types from Python to Qt format.
Primitive types are kept as they are.
List types are converted to list type.
Pydantic types are converted to dict type.
Other types are converted to dict type.
- Returns:
Tuple[List[str], List[type]] - argument names and argument types.
- static from_py_to_web(arg) Any [source]ο
Converts a Python format argument to a web format argument.
- Returns:
Primitive types are kept as they are.
List types are recursively converted using the inner type.
Pydantic types are converted to a dictionary using the dict() method.
Other types are converted to a dictionary using the dict() method.
- static from_py_to_web_response(result) Dict[str, Any] [source]ο
- Converts a Python format result to a web format response.
String types are wrapped in a Response object with success attribute.
Response types are converted to a dictionary using the dict() method.
Other types are wrapped in a Response object with data attribute.
- Returns:
Dict[str, Any] - a dictionary that represents the response.
- static from_web_to_py(arg, paramType) Any [source]ο
Converts a web format argument to a Python format argument according to the given parameter type.
- Returns:
Primitive types are kept as they are.
List types are recursively converted using the inner type.
Pydantic types are instantiated using the argument as a keyword dictionary.
Other types are kept as they are.
- class pywebchannel.Controller.EmitBy[source]ο
Bases:
object
A class to represent the source of a notification.
- Auto = 0ο
- User = 1ο
- class pywebchannel.Controller.Helper[source]ο
Bases:
object
- static infer_caller_info(stack: List[FrameInfo]) Tuple[str, str] [source]ο
A method that infers the name of the controller and the variable that called this method from the stack trace.
- Parameters:
stack (List[inspect.FrameInfo]) β A list of frame information objects representing the current call stack.
- Returns:
A tuple of two strings: the name of the controller and the name of the variable that called this method. If the variable name cannot be inferred, an empty string is returned as the second element of the tuple.
- Return type:
- class pywebchannel.Controller.Notify(arguments: Dict[str, type] | List[type], name: str = None, emitBy: EmitBy = 0)[source]ο
Bases:
object
A class to represent a notification object.
- argumentsο
A dictionary of the arguments that the notification expects, with the argument
- name as the key and the argument type as the value.
- The default value is EmitBy.Auto.
- pywebchannel.Controller.Property(p_type: type, init_val=None, get_f=None, set_f=None) Property [source]ο
A function that creates a Qt property and a corresponding signal. The function is responsible for creating the backend variable, getter and setter functions, and the signal object related with the property.
- Parameters:
p_type (type) β The type of the property value.
init_val β The initial value of the property. Defaults to None
get_f (function, optional) β A custom getter function for the property. Defaults to None.
set_f (function, optional) β A custom setter function for the property. Defaults to None.
- Returns:
The prop which is a QtCore.Property object.
- Raises:
Exception β If the property name cannot be inferred from the caller information
References
https://doc.qt.io/qtforpython-6/PySide6/QtCore/Property.html
See also
Signal, Action
- class pywebchannel.Controller.Response(*, success: str | None = None, error: str | None = None, data: Any | None = None)[source]ο
Bases:
BaseModel
A Pydantic model that represents the outcome of some operation.
- data: Any | Noneο
Any Python object that stores the result of the operation. It can be of any type, such as a dict, a list, a tuple, a string, a number, etc. Pydantic will not perform any validation or conversion on this field.
- error: str | Noneο
A string that provides an error message if something went wrong during the operation. It can be None or any string value. For example, βInvalid inputβ, βConnection timeoutβ, βDatabase errorβetc.
- model_config: ClassVar[ConfigDict] = {}ο
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[dict[str, FieldInfo]] = {'data': FieldInfo(annotation=Union[Any, NoneType], required=False), 'error': FieldInfo(annotation=Union[str, NoneType], required=False), 'success': FieldInfo(annotation=Union[str, NoneType], required=False)}ο
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].
This replaces Model.__fields__ from Pydantic V1.
- pywebchannel.Controller.Signal(args: Dict[str, type] | List[type], controllerName: str = None, signalName: str = None) Signal [source]ο
A function that creates a Qt signal with the given arguments by making necessary type conversions to keep Qt and serialization process happy.
- Parameters:
- Returns:
A QtCore.Signal object with the specified arguments, name, and arguments names.
- Raises:
Exception β If the controller name or signal name cannot be inferred from the caller information, or if the signal name is empty.
References
https://doc.qt.io/qtforpython-6/PySide6/QtCore/Signal.html
See also
Property, Action
- class pywebchannel.Controller.Type[source]ο
Bases:
object
This class provides some utility methods to check the type of variable.
- is_primitive(var_type
type) -> bool: Returns True if the given type is a primitive type, False otherwise.
- is_list(var_type
type) -> bool: Returns True if the given type is a list type, False otherwise.
- is_pydantic(var_type
type) -> bool: Returns True if the given type is a subclass of pydantic.BaseModel, False otherwise.
- primitives = (<class 'bool'>, <class 'str'>, <class 'int'>, <class 'float'>, <class 'NoneType'>)ο
A tuple of primitive types in Python, such as bool, str, int, float, and NoneType.
GeneratorWatcherο
- class pywebchannel.GeneratorWatcher.GeneratorWatcher(parent: QObject | None = None)[source]ο
Bases:
QFileSystemWatcher
A class that inherits from QFileSystemWatcher and watches for changes in python files.
- watchTargetDirMapο
A dictionary that maps the source directory to the target directory.
- addDirectory(dirPathToWatch: str, dirTargetPath: str)[source]ο
A method that adds a directory to the watch list.
- addFile(filePath: str)[source]ο
A method that adds a file to the watch list.
- Parameters:
filePath (str) β The path of the file to watch.
- onDirectoryChanged(dirPath: str)[source]ο
The slot that is triggered when a directory is changed.
- Parameters:
dirPath (str) β The path of the changed directory.
- onFileChanged(filePath: str)[source]ο
The slot that is triggered when a file is changed.
- Parameters:
filePath (str) β The path of the changed file.
- staticMetaObject = PySide6.QtCore.QMetaObject("GeneratorWatcher" inherits "QFileSystemWatcher": Methods: #9 type=Slot, signature=onDirectoryChanged(QString), parameters=QString #10 type=Slot, signature=onFileChanged(QString), parameters=QString )ο
WebChannelServiceο
- class pywebchannel.WebChannelService.WebChannelService(serviceName: str, parent: QObject | None = None)[source]ο
Bases:
QObject
A class that inherits from QObject and provides a web channel service using QWebSocketServer and QWebChannel.
- websocketServerο
The QWebSocketServer object that provides the WebSocket server.
- Type:
QWebSocketServer
- clientWrapperο
The WebSocketClientWrapper object that handles the WebSocket connections from the server.
- Type:
- channelο
The QWebChannel object that manages the communication between the server and the clients.
- Type:
QWebChannel
- isOnline() bool [source]ο
Checks if the web channel service is online by checking the status of the WebSocket server.
- Returns:
True if the web channel service is online, False otherwise.
- Return type:
- onClientConnected(transport: WebSocketTransport) None [source]ο
Connects the web channel to the WebSocket transport and increments the active client count.
This slot is invoked when the clientWrapper object emits the clientConnected signal.
- Parameters:
transport (WebSocketTransport) β The WebSocketTransport object that represents the WebSocket connection.
- onClientDisconnected(transport: WebSocketTransport) None [source]ο
Decrements the active client count and cleans up the controller objects if the active client count is zero.
This slot is invoked when the clientWrapper object emits the clientDisconnected signal.
- Parameters:
transport (WebSocketTransport) β The WebSocketTransport object that represents the WebSocket connection.
- onClosed() None [source]ο
Logs the information of closing the web channel service.
This slot is invoked when the websocketServer object emits the closed signal.
- registerController(controller: Controller) None [source]ο
Registers a controller object to the web channel using the channel attribute.
- Parameters:
controller (Controller) β The controller object to be registered.
- start(port: int) bool [source]ο
Starts the web channel service by creating and listening to a WebSocket server at the given port.
- staticMetaObject = PySide6.QtCore.QMetaObject("WebChannelService" inherits "QObject": Methods: #5 type=Slot, signature=onClosed() #6 type=Slot, signature=onClientConnected(QWebChannelAbstractTransport*), parameters=QWebChannelAbstractTransport* #7 type=Slot, signature=onClientDisconnected(QWebChannelAbstractTransport*), parameters=QWebChannelAbstractTransport* )ο
- class pywebchannel.WebChannelService.WebSocketClientWrapper(server: QWebSocketServer, parent: QObject | None = None)[source]ο
Bases:
QObject
A class that inherits from QObject and handles the WebSocket connections from a QWebSocketServer.
- serverο
The QWebSocketServer object that listens for WebSocket connections.
- Type:
QWebSocketServer
- clientConnectedο
The signal that is emitted when a new WebSocket connection is established.
- clientDisconnectedο
The signal that is emitted when an existing WebSocket connection is closed.
- handleNewConnection() None [source]ο
Creates a WebSocketTransport object for the next pending connection from the server and emits the clientConnected signal.
This slot is invoked when the server object emits the newConnection signal.
- staticMetaObject = PySide6.QtCore.QMetaObject("WebSocketClientWrapper" inherits "QObject": Methods: #5 type=Signal, signature=clientConnected(QWebChannelAbstractTransport*), parameters=QWebChannelAbstractTransport* #6 type=Signal, signature=clientDisconnected(QWebChannelAbstractTransport*), parameters=QWebChannelAbstractTransport* #7 type=Slot, signature=handleNewConnection() )ο
- class pywebchannel.WebChannelService.WebSocketTransport(socket: QWebSocket)[source]ο
Bases:
QWebChannelAbstractTransport
A class that inherits from QWebChannelAbstractTransport and communicates with a QWebSocket.
- socketο
The QWebSocket object that handles the WebSocket connection.
- Type:
QWebSocket
- disconnectedο
The signal that is emitted when the socket is disconnected.
- onSocketDisconnected() None [source]ο
Emits the disconnected signal with the self object and deletes the self object and the socket object.
This slot is invoked when the socket object emits the disconnected signal.
- sendMessage(message) None [source]ο
Sends a message to the WebSocket using the socket object.
The message is converted to a QJsonDocument and then to a compact JSON string.
- Parameters:
message β The message to be sent.
- staticMetaObject = PySide6.QtCore.QMetaObject("WebSocketTransport" inherits "QWebChannelAbstractTransport": Methods: #7 type=Signal, signature=disconnected(QWebChannelAbstractTransport*), parameters=QWebChannelAbstractTransport* #8 type=Slot, signature=onSocketDisconnected() #9 type=Slot, signature=textMessageReceived(QString), parameters=QString )ο
- textMessageReceived(messageData: str) None [source]ο
Receives a text message from the WebSocket using the socket object and emits the messageReceived signal.
The text message is parsed as a QJsonDocument and then as a QJsonObject. If there is any error in parsing, the error is logged using the Logger object.
This slot is invoked when the socket object emits the textMessageReceived signal.
- Parameters:
messageData (str) β The text message received from the WebSocket.
HttpServerο
- class pywebchannel.HttpServer.HttpServer(serverDir: str, port: int, parent=None)[source]ο
Bases:
QObject
A class that inherits from QObject and runs an HTTP server using QProcess.
- processο
The QProcess object that executes the HTTP server.
- Type:
QProcess
- onReadyReadStandardError() None [source]ο
Reads the standard error from the QProcess object and logs it using the Logger object.
This slot is invoked when the QProcess object emits the readyReadStandardError signal.
- onReadyReadStandardOutput() None [source]ο
Reads the standard output from the QProcess object and logs it using the Logger object.
This slot is invoked when the QProcess object emits the readyReadStandardOutput signal.
- start() None [source]ο
Starts the HTTP server using the QProcess object.
The QProcess object executes the command βpython -m http.server port βdirectory serverDirβ.
- staticMetaObject = PySide6.QtCore.QMetaObject("HttpServer" inherits "QObject": Methods: #5 type=Slot, signature=stop() #6 type=Slot, signature=onReadyReadStandardOutput() #7 type=Slot, signature=onReadyReadStandardError() )ο
CodeAnalyzerο
- class pywebchannel.CodeAnalyzer.CodeAnalyzer(MetaClass)[source]ο
Bases:
object
A class that analyzes the code of a given class and determines its type and acceptability.
- _isAcceptableο
A flag indicating whether the class object is acceptable for analysis or not.
- Type:
- classType()[source]ο
Returns the type of the class object, one of the supported types.
- Returns:
The type of the class object, or an empty string if not acceptable.
- Return type:
- class pywebchannel.CodeAnalyzer.ControllerInterface(MetaClass)[source]ο
Bases:
Interface
A class that represents the interface of a controller class.
A controller class is a subclass of QObject that defines properties, signals, and slots that can be used to communicate with other classes or components.
- class pywebchannel.CodeAnalyzer.Interface(MetaClass)[source]ο
Bases:
object
A base class that represents the interface of a class.
An interface is a set of properties, signals, and slots that define the communication and functionality of a class.
- staticMetaObjectο
The static meta-object of the meta class.
- Type:
QMetaObject
- class pywebchannel.CodeAnalyzer.ModelInterface(MetaClass)[source]ο
Bases:
Interface
A class that represents the interface of a model class.
- class pywebchannel.CodeAnalyzer.Parameter(name: str, typeStr: str)[source]ο
Bases:
object
A class to represent a parameter in TypeScript.
- class pywebchannel.CodeAnalyzer.Signal(name: str, parameters: list[Parameter], returnType: Return)[source]ο
Bases:
object
- class pywebchannel.CodeAnalyzer.Slot(name: str, parameters: list[Parameter], returnType: Return)[source]ο
Bases:
object
A class to represent a slot of a TypeScript class.
- parametersο
A list of Parameter objects that represent the parameters of the slot function.
Utilsο
- class pywebchannel.Utils.Generator[source]ο
Bases:
object
A class to generate TypeScript code for interfaces.
- static header()[source]ο
Generate the header for the TypeScript file.
- Returns:
A list of strings that represent the header lines.
- Return type:
- class pywebchannel.Utils.Logger[source]ο
Bases:
object
A class to log messages with different colors and levels.
- static error(message, sender='') None [source]ο
Log an error message with red color and optional sender name.
- static info(message, sender='') None [source]ο
Log an info message with green color and optional sender name.
- class pywebchannel.Utils.Utils[source]ο
Bases:
object
A class that provides some utility methods for working with types and signatures.
- VARIABLE_TYPE_MAP = {'QString': 'string', 'QVariantList': 'any[]', 'QVariantMap': 'any', 'Response': 'Response', 'any': 'any', 'bool': 'boolean', 'dict': 'any', 'double': 'number', 'float': 'number', 'int': 'number', 'list': 'any[]', 'str': 'string', 'void': 'void'}ο
- static convertType(text) str [source]ο
Converts a Python type to a TypeScript type using the VARIABLE_TYPE_MAP.
- Parameters:
text β A string that represents the Python type to be converted.
- Returns:
A string that represents the TypeScript type, with the format β<type>[]β for list types.
- static getInheritanceTree(T: type)[source]ο
Returns a dictionary that represents the inheritance tree of a given type.
- Parameters:
T β A type object that represents the subclass.
Returns: A dictionary that maps the names of the base classes to their type objects, starting from the subclass to the object class.
- static isList(text: str) tuple[bool, str] [source]ο
Checks if a string representation of a type is a list type.
- Parameters:
text β A string that represents the type to be checked.
- Returns:
A tuple of a boolean value and a string prefix. The boolean value is True if the type is a list type, and False otherwise. The string prefix is either list[ or List[ depending on the case of the type, or an empty string if the type is not a list type.
- static isTypescriptPrimitive(text: str) bool [source]ο
Checks if a string representation of a type is a TypeScript primitive type.
- Parameters:
text β A string that represents the type to be checked.
- Returns:
A boolean value that is True if the type is a TypeScript primitive type, and False otherwise.
- static parseWithInspect(f)[source]ο
Parses the signature of a function using the inspect module.
- Parameters:
f (function) β The function to be parsed.
- Returns:
The names of the parameters of the function. paramTypes (list of str): The types of the parameters of the function, or empty strings if not annotated. returnType (str): The type of the return value of the function, or βResponseβ if not annotated.
- Return type:
- pp = <pprint.PrettyPrinter object>ο
- static simplyVariableType(text: str) str [source]ο
Simplifies a str representation of a type by removing whitespace, quotation marks, and package information.
- Parameters:
text β A string that represents the type to be simplified.
- Returns:
A simplified string that represents the type, with the format βlist[<type>]β for list types.