API Reference
API Reference
This document describes in detail all API interfaces provided by the Python SDK, including complete API references for the core features, configuration management, the logging system, exception handling and other modules.
Core Features
- Full coverage: covers every core API and utility function
- Detailed documentation: every API comes with complete parameter descriptions and examples
- Practical examples: real-world usage cases
- Type safety: complete type annotations and parameter validation
- High performance: optimized implementations and best-practice guidance
API Categories at a Glance
| Module | Description | Main features |
|---|---|---|
| ServerApplication | Server application core | App initialization, route management, middleware |
| GConfig | Configuration management | Config file loading, environment variables, dynamic config |
| GLogger | Logging system | Structured logs, multiple outputs, performance monitoring |
| RPCException | Exception handling | Custom exceptions, error codes, exception chains |
| Middleware System | Request processing | Authentication, rate limiting, CORS, request logging |
| Utility Functions | Helper features | Data validation, formatting, encryption and decryption |
simplejrpc Module
ServerApplication Class
ServerApplication is a JSON-RPC server application class used to create and manage RPC services built on Unix domain sockets. The class provides configuration management, route registration, parameter validation, middleware support and logger setup.
Core Features
- Route management: supports registering RPC methods with decorators
- Parameter validation: built-in form validation
- Middleware support: an extensible request processing pipeline
- Configuration management: supports multiple configuration file formats
- Logging integration: built-in logging
Quick Start
from simplejrpc import ServerApplication
# Create a server instance
app = ServerApplication("/tmp/rpc.sock")
# Register an RPC method
@app.route("hello")
def hello(name: str):
return f"Hello, {name}!"
# Start the server
app.run()__init__(socket_path: str, config: Optional[object] = Settings(), config_path: Optional[str] = None)
Initializes a ServerApplication instance.
Parameters:
socket_path: string, path to the Unix domain socketconfig: optional, configuration object, defaults to a Settings() instanceconfig_path: optional, string, path to the configuration file
Returns: None
Example:
# Basic initialization
app = ServerApplication("/tmp/my_rpc.sock")
# Initialize with a configuration file
app = ServerApplication(
socket_path="/tmp/my_rpc.sock",
config_path="config.yaml"
)
# Use a custom configuration object
from simplejrpc import Settings
config = Settings({"debug": True})
app = ServerApplication("/tmp/my_rpc.sock", config=config)from_config(config_content: Optional[Dict[str, Any]] = None, config_path: Optional[str] = None)
Loads configuration from configuration content or from a configuration file.
Parameters:
config_content: optional, dict, configuration contentconfig_path: optional, string, path to the configuration file
Returns:
- The configuration object (a Settings instance)
route(name: Optional[str] = None, form: Optional[Form] = BaseForm, fn=None)
Route decorator used to register RPC methods and provide parameter validation.
Parameters:
name: optional, string, RPC method name, defaults to the function nameform: optional, Form type, the form class used for parameter validation, defaults to BaseFormfn: optional, the function being decorated
Returns:
- The decorated function
Example:
from simplejrpc import ServerApplication, BaseForm
from typing import Optional
app = ServerApplication("/tmp/rpc.sock")
# Basic route registration
@app.route()
def get_user_info(user_id: int):
return {"user_id": user_id, "name": "John Doe"}
# Custom method name
@app.route("user.create")
def create_user(name: str, email: str):
return {"id": 123, "name": name, "email": email}
# Use form validation
class UserForm(BaseForm):
name: str
email: str
age: Optional[int] = None
@app.route("user.update", form=UserForm)
def update_user(data: UserForm):
return {"success": True, "data": data.dict()}load_config(config_path: str)
Loads a configuration file from the given path. YAML, JSON and INI configuration files are supported.
Parameters:
config_path: string, path to the configuration file
Returns:
- A dict with the configuration content
Raises:
- Raises FileNotFoundError if the file does not exist
- Raises ValueError if the file format is not supported
Supported configuration file formats:
- YAML (.yml, .yaml)
- INI (.ini)
- JSON (.json)
Example:
app = ServerApplication("/tmp/rpc.sock")
# Load a YAML configuration file
app.load_config("config.yaml")
# Load a JSON configuration file
app.load_config("config.json")
# Example configuration file (config.yaml)
# debug: true
# log_level: "INFO"
# max_connections: 100
# timeout: 30setup_logger(config_content: Dict[str, Any])
Sets up the logger from configuration content.
Parameters:
config_content: dict, configuration content
Returns: None
Note:
- The configuration must contain a "logger" section, and the "sink" parameter is required
clear_socket()
Cleans up the Unix domain socket.
Parameters: None
Returns: None
middleware(middleware_instance: RPCMiddleware)
Registers middleware. Middleware runs in the order it was added and supports request preprocessing and response postprocessing.
Parameters:
middleware_instance: an RPCMiddleware instance, the middleware object
Returns:
- The server instance
Example:
from simplejrpc import ServerApplication
import time
app = ServerApplication("/tmp/rpc.sock")
# A simple logging middleware
def logging_middleware(request, call_next):
start_time = time.time()
print(f"请求开始: {request.method}")
response = call_next(request)
duration = time.time() - start_time
print(f"请求完成: {request.method}, 耗时: {duration:.3f}s")
return response
# An authentication middleware
def auth_middleware(request, call_next):
# Check the credentials
if not request.headers.get("Authorization"):
raise RPCException("未授权访问", code=-32001)
return call_next(request)
# Add the middleware
app.middleware(logging_middleware)
app.middleware(auth_middleware)run()
Starts the RPC server and registers a callback that cleans up the socket on exit. The method blocks the current thread and starts listening on the given Unix domain socket.
Parameters: None
Returns: None
Example:
from simplejrpc import ServerApplication
app = ServerApplication("/tmp/rpc.sock")
@app.route("ping")
def ping():
return "pong"
# Start the server (runs blocking)
print("启动 RPC 服务器...")
app.run()Note
- The
run()method blocks the current thread - Make sure the socket path has the proper permissions
- The server cleans up any existing socket file automatically before it starts
Settings Class
Settings is a configuration management class used to process and access application configuration. It offers a simple interface for retrieving configuration items and configuration sections.
Configuration Features
- Multiple sources: dicts, files and environment variables
- Type validation: automatic type checking and conversion
- Defaults: sensible default configuration
- Environment variables: environment variable overrides
- Config merging: several sources merged intelligently
Configuration Precedence
Configuration loading precedence (highest to lowest):
- Environment variables
- Configuration file
- Configuration dict in code
- Defaults
__init__(config_content: Dict[str, Any] = None)
Initializes a Settings instance.
Parameters:
config_content: optional, dict, configuration content. If it is None, an empty dict is used.
Returns: None
Example:
from simplejrpc import Settings
# Use the default configuration
settings = Settings()
# Use a custom configuration
config = {
"debug": True,
"log_level": "DEBUG",
"max_connections": 50,
"timeout": 60
}
settings = Settings(config)
# Access configuration values
print(f"调试模式: {settings.debug}")
print(f"日志级别: {settings.log_level}")get_section(key: str, default=None) -> Dict[str, Any]
Retrieves the configuration section for the given key. Dotted keys are supported for nested lookups.
Parameters:
key: string, the key of the configuration section (nested keys such as "server.database" are supported)default: optional, the value returned when the key does not exist
Returns:
- A dict with the configuration section, or the default value when the key does not exist
Example:
from simplejrpc import Settings
config = {
"server": {
"host": "localhost",
"port": 8080,
"database": {
"url": "sqlite:///app.db",
"pool_size": 10
}
},
"logging": {
"level": "INFO",
"format": "%(asctime)s - %(levelname)s - %(message)s"
}
}
settings = Settings(config)
# Get the server configuration section
server_config = settings.get_section("server", {})
print(f"服务器配置: {server_config}")
# Get the database configuration section
db_config = settings.get_section("server.database", {})
print(f"数据库配置: {db_config}")
# Get a section that does not exist (returns the default)
cache_config = settings.get_section("cache", {"enabled": False})
print(f"缓存配置: {cache_config}")get_config_object()
Retrieves the whole configuration object.
Parameters: None
Returns:
- A configuration object of type DefaultMapping
get_option(key: str) -> DefaultMapping
Retrieves the configuration option for the given key.
Parameters:
key: string, the key of the configuration option
Returns:
- A configuration option of type DefaultMapping
Example:
from simplejrpc import Settings
config = {
"server": {
"host": "localhost",
"port": 8080
}
}
settings = Settings(config)
# Get the server configuration option
server_option = settings.get_option("server")
print(f"主机: {server_option.host}")
print(f"端口: {server_option.port}")
# Access it through attributes
print(f"服务器地址: {server_option.host}:{server_option.port}")Notes
- Configuration content is converted into a DefaultMapping object, which can be accessed through attributes
- Accessing a configuration item that does not exist raises an attribute error
- You can pass a default value to
get_sectionto avoid errors when a configuration section does not exist
GConfig Class
GConfig is a global configuration management class that provides a unified configuration access interface. The class uses the singleton pattern so configuration stays consistent across the whole application.
Global Configuration Features
- Singleton pattern: one global configuration instance
- Unified interface: a consistent way to read configuration
- Automatic loading: loads from several configuration sources
- Thread safety: works in multithreaded environments
- Dynamic updates: configuration can be updated at runtime
Use Cases
- Application-wide configuration management
- Configuration sharing across modules
- Centralized configuration management
- Swapping configuration per environment
__init__(config_content: Optional[Dict[str, Any]] = None, config_path: Optional[str] = None)
Initializes a GConfig instance. Because of the singleton pattern, repeated initialization returns the same instance.
Parameters:
config_content: optional, dict, configuration contentconfig_path: optional, string, path to the configuration file
Returns: None
Example:
from simplejrpc import GConfig
# Option 1: initialize with a configuration dict
config_data = {
"app": {
"name": "MyApp",
"version": "1.0.0",
"debug": True
},
"database": {
"host": "localhost",
"port": 5432,
"name": "mydb"
}
}
config = GConfig(config_content=config_data)
# Option 2: initialize with a configuration file
config = GConfig(config_path="config.yaml")
# Option 3: combine both (configuration file + extra configuration)
config = GConfig(
config_path="config.yaml",
config_content={"debug": True}
)
# Singleton check
config1 = GConfig()
config2 = GConfig()
print(config1 is config2) # Trueget_instance()
Retrieves the GConfig singleton instance. A new instance is created when none exists yet.
Parameters: None
Returns:
- A GConfig instance
Example:
from simplejrpc import GConfig
# Get the global configuration instance
config = GConfig.get_instance()
# Get the same instance in another module
# module_a.py
def get_app_name():
config = GConfig.get_instance()
return config.get("app.name", "Unknown")
# module_b.py
def get_db_config():
config = GConfig.get_instance()
return config.get_section("database", {})
# Both modules access the same configuration instance
print(get_app_name()) # MyApp
print(get_db_config()) # {"host": "localhost", "port": 5432, ...}get(key: str, default: Any = None)
Gets a configuration value. Dotted keys are supported for nested lookups.
Parameters:
key: string, the configuration key (nested keys such as "app.database.host" are supported)default: any type, the default value
Returns:
- The configuration value or the default value
Example:
from simplejrpc import GConfig
# Initialize the configuration
config_data = {
"app": {
"name": "MyRPCApp",
"version": "2.1.0",
"features": {
"auth": True,
"cache": False
}
},
"server": {
"host": "0.0.0.0",
"port": 8080,
"workers": 4
}
}
config = GConfig(config_content=config_data)
# Get a simple value
app_name = config.get("app.name", "DefaultApp")
print(f"应用名称: {app_name}")
# Get a nested value
auth_enabled = config.get("app.features.auth", False)
print(f"认证功能: {auth_enabled}")
# Get server settings
server_host = config.get("server.host", "localhost")
server_port = config.get("server.port", 3000)
print(f"服务器: {server_host}:{server_port}")
# Get a value that does not exist (the default is used)
timeout = config.get("server.timeout", 30)
print(f"超时时间: {timeout}秒")get_section(key: str, default: Dict[str, Any] = None)
Gets a configuration section. Returns the whole configuration section for the given key.
Parameters:
key: string, the configuration section keydefault: dict, the default value
Returns:
- The configuration section dict or the default value
Example:
from simplejrpc import GConfig
config = GConfig.get_instance()
# Get the whole database configuration section
db_config = config.get_section("database", {})
print(f"数据库配置: {db_config}")
# Get the application configuration section
app_config = config.get_section("app", {})
print(f"应用配置: {app_config}")set(key: str, value: Any)
Sets a configuration value. Configuration can be updated dynamically at runtime.
Parameters:
key: string, the configuration keyvalue: any type, the configuration value
Returns: None
Example:
from simplejrpc import GConfig
config = GConfig.get_instance()
# Set a simple value
config.set("app.debug", True)
config.set("server.port", 9000)
# Set a nested value
config.set("app.features.logging", True)
# Verify the values
print(config.get("app.debug")) # True
print(config.get("server.port")) # 9000Notes
- GConfig uses the singleton pattern so the global configuration stays consistent
- Several configuration sources are supported: dicts, files and environment variables
- Keys support dotted access to nested values
- Thread-safe, so it can be used in multithreaded environments
- Configuration can be updated dynamically at runtime
JsonRpcServer Class
JsonRpcServer is a JSON-RPC server implementation built on Unix domain sockets that handles RPC requests and responses. The class provides middleware support, request handling, response serialization and error handling.
__init__(socket_path: str)
Initializes a JsonRpcServer instance.
Parameters:
socket_path: string, path to the Unix domain socket
Returns: None
to_serializable(response: ResponseType)
Converts a response object into a serializable object.
Parameters:
response: ResponseType, the response object
Returns:
- A serializable response object
middleware(middleware_instance: RPCMiddleware)
Registers middleware.
Parameters:
middleware_instance: an RPCMiddleware instance, the middleware object
Returns:
- The middleware instance
dispatch_to_response(*args, serializer=json.dumps, post_process=None, **kwargs)
Dispatches a request and produces a response.
Parameters:
*args: variadic, the request dataserializer: optional, callable, the serialization function, defaults to json.dumpspost_process: optional, callable, a post-processing function**kwargs: keyword arguments, other parameters
Returns:
- The serialized response string
handle_client(reader, writer)
Handles a client connection.
Parameters:
reader: a StreamReader object used to read data from the clientwriter: a StreamWriter object used to write data to the client
Returns: None
clear_socket()
Cleans up the Unix domain socket.
Parameters: None
Returns: None
start_server(f_socket)
Starts the server.
Parameters:
f_socket: string, the socket path
Returns: None
Raises:
- Raises RuntimeError if the socket path is not configured
run()
Runs the server.
Parameters: None
Returns: None
Notes
- The server communicates over a Unix domain socket
- A middleware mechanism is supported for handling requests and responses
- Error handling and logging are provided
- The socket file is cleaned up automatically
ClientTransport Class
ClientTransport is an abstract base class that defines the interface of the RPC client transport layer. It defines the basic methods a client needs in order to communicate with a server.
send_message(message: Union[Dict[str, Any], str])
Sends a message to the server.
Parameters:
message: dict or string, the message to send- a dict means a JSON-RPC request is sent
- a string means the raw string message is sent
Returns: None
close()
Closes the client connection.
Parameters: None
Returns: None
connect()
Establishes the connection to the server.
Parameters: None
Returns: None
Notes
- This is an abstract base class and every method is asynchronous (it uses the
asynckeyword) - A concrete implementation that inherits from this class must implement every abstract method
- Every method uses the
@abstractmethoddecorator, which means it must be overridden in a subclass
UnixSocketTransport Class
UnixSocketTransport is a transport layer implementation built on Unix domain sockets that inherits from the ClientTransport abstract base class. It provides the concrete implementation used to communicate with an RPC
server.
__init__(socket_path: str)
Initializes a UnixSocketTransport instance.
Parameters:
socket_path: string, path to the Unix domain socket
Returns: None
connect()
Establishes the asynchronous connection to the server.
Parameters: None
Returns: None
make_header(message: str)
Builds the message header.
Parameters:
message: string, the message to send
Returns: None
make_body(body: str)
Builds the message body.
Parameters:
body: string, the message body
Returns: None
send_message(message)
Sends a message and receives the response.
Parameters:
message: dict or string, the message to send- a dict is converted into a JSON string automatically
Returns:
- The server response (the parsed JSON object)
read_from_header()
Reads the message header.
Parameters: None
Returns:
- The header content as bytes, up to
\r\n\r\n
read_content_length_from_header(header: str)
Parses the content length from the header.
Parameters:
header: string, the message header
Returns:
- The content length as an integer
_read_response()
Reads the complete response message.
Parameters: None
Returns:
- The parsed JSON response object
close()
Closes the connection.
Parameters: None
Returns: None
Notes
- All network operations are asynchronous and must be used in an async context
- The message format follows the Content-Length header protocol
- Automatic JSON serialization and deserialization are supported
- You must call close() manually when you are done
Request Class
Request is an RPC client request class used to send JSON-RPC requests and handle responses. The class supports both synchronous and asynchronous usage.
__init__(socket_path: str, adapter: Optional[ClientTransport] = None)
Initializes a Request instance.
Parameters:
socket_path: string, path to the Unix domain socketadapter: optional, a ClientTransport instance, defaults to None, in which case a new UnixSocketTransport instance is created
Returns: None
make_session()
Creates a connection session with the server.
Parameters: None
Returns: None
send_request(method: str, params: Union[Dict[str, Any], Tuple[Any, ...], None] = None, id: Any = NOID)
Sends an RPC request synchronously (it runs the async request internally with asyncio.run).
Parameters:
method: string, the RPC method nameparams: optional, dict or tuple, the RPC method parametersid: optional, the request ID, defaults to NOID
Returns:
- The server response
Notes
- The class supports both synchronous and asynchronous calls
- Every request opens a new connection and closes it when the request is done
async_send_requestmust be called from an async contextsend_requestcan be called from synchronous code- You can implement a different transport by supplying a custom adapter
GmRequest Class
GmRequest is a dedicated request class that inherits from Request and handles specific GM (Game Master) requests. It is initialized with the default GM socket path.
__init__(socket_path=DEFAULT_GA_SOCKET, adapter=None)
Initializes a GmRequest instance.
Parameters:
socket_path: optional, string, path to the Unix domain socket, defaults to DEFAULT_GA_SOCKETadapter: optional, a ClientTransport instance, defaults to None
Returns: None
Notes
- The class inherits every feature of the
Requestclass - It uses the default GM socket path (DEFAULT_GA_SOCKET)
- You can implement a different transport by supplying a custom adapter
- It is mainly used for GM-related RPC requests
RPCException Class
RPCException is a base RPC exception class that inherits from Python's built-in Exception class. It handles the various error situations that can occur during RPC calls and provides a unified error response format.
__init__(message=http.HTTPStatus.BAD_REQUEST.description, code=http.HTTPStatus.BAD_REQUEST.value, data: Optional[str] = None, *args, **kwargs)
Initializes an RPCException instance.
Parameters:
message: string, the error message, defaults to the description of HTTP 400 Bad Requestcode: integer, the error code, defaults to the status code of HTTP 400 Bad Requestdata: optional, string, additional error data*args: variadic positional arguments passed to the parent Exception**kwargs: variadic keyword arguments, additional parameters
Returns: None
__str__()
Converts the exception into its string representation.
Parameters: None
Returns:
- A JSON string with the following fields:
code: the error codedata: the error data (if any)msg: the error message
Notes
- This class is the base exception class; other specific RPC exceptions should inherit from it
- Error responses are serialized to JSON automatically
- It uses the status code and description of HTTP 400 Bad Request by default
- Custom error data can be passed through
RPC Exception Classes
The following are the RPC-related exception classes. All of them inherit from the base RPCException class.
UnauthorizedError
Unauthorized exception, used for authentication and authorization failures.
Inherits: RPCException
ValidationError
Validation exception, used when parameter validation fails.
Inherits: RPCException
FileNotFoundError
File-not-found exception, used for errors related to file operations.
Inherits: RPCException
ValueError
Value error exception, used for invalid parameter values.
Inherits: RPCException
RuntimeError
Runtime error exception, used for general errors while the program runs.
Inherits: RPCException
AttributeError
Attribute error exception, used when accessing an attribute that does not exist.
Inherits: RPCException
Notes
- All exception classes inherit from
RPCException, so they all share the same base behaviour - Each exception class accepts a custom error message, error code and extra data
- Exception information is serialized to JSON automatically
- The status code and description of HTTP 400 Bad Request are used by default
- These exception classes provide fine-grained error handling, so you can pick the class that matches the situation
Language Class
Language is a string enum class that defines the supported language codes. It inherits from str and enum.Enum and provides a standardized representation of language codes.
Enum Values
EN: English ("en")JA: Japanese ("ja")RU: Russian ("ru")ZH_CN: Simplified Chinese ("zh-CN")ZH_TW: Traditional Chinese ("zh-TW")
values()
Gets all supported language code values.
Parameters: None
Returns:
- A list containing the string value of every language code
Notes
- The language codes follow the standard language identifier format
- Five main languages are supported: English, Japanese, Russian, Simplified Chinese and Traditional Chinese
- You can access a language code directly through the enum member
- The values() method returns the list of all supported language codes
GI18n Class
GI18n is an internationalization (i18n) management class that provides convenient multi-language translation and resource loading. The class wraps the features of the T class behind a more compact interface.
__init__(path: str, lang: str, adapter: TranslateBase = None)
Initializes a GI18n instance.
Parameters:
path: string, location of the i18n configuration filelang: string, i18n language settingadapter: optional, TranslateBase type, a custom i18n translator
Returns: None
translate(key) -> str
Gets the translation for the given key.
Parameters:
key: the translation key
Returns:
- The translation text as a string
get_lang() -> str
Gets the current language setting.
Parameters: None
Returns:
- The current language code as a string
set_path(path: str)
Sets the i18n configuration file path.
Parameters:
path: string, the configuration file path
Returns: None
set_lang(lang: str)
Sets the current language.
Parameters:
lang: string, the language code
Returns: None
translate_ctx(key, *value) -> str
Gets a translation with context arguments.
Parameters:
key: the translation key*value: variadic, used to format the translated text
Returns:
- The formatted translation text as a string
translate_load(file: Union[str, Path], ignore=False) -> str
Loads translations from a file.
Parameters:
file: string or Path, the translation file pathignore: boolean, whether to ignore a missing file error, defaults to False
Returns:
- The translation text as a string
translate_load_partial(file: Path, ignore=False) -> str
Loads partial translations from a file.
Parameters:
file: Path, the translation file pathignore: boolean, whether to ignore a missing file error, defaults to False
Returns:
- The translation text as a string
translate_app_info(file_root: Path, filename: str) -> str
Loads the translations for application information.
Parameters:
file_root: Path, the root directory of the translation filesfilename: string, the translation file name
Returns:
- The translation text as a string
Notes
- The class wraps the
Tclass behind a more compact interface - Custom translation adapters are supported
- Translations can be loaded from files
- Translation with format arguments is available
- The language and the configuration file path can be switched at runtime
T Class
T is the core internationalization (i18n) class. It provides the basic text translation features and supports several translation sources and a caching mechanism.
Class Attributes
I18n_ROOT: Path, the root directory of the i18n filesLANG: Language, the current language setting, defaults to English (EN)Translate: DefaultTranslate, the translator implementation class
Translation Methods
translate(key: str)
Gets the translation for the given key.
Parameters:
key: string, the translation key
Returns:
- The translated text
translate_ctx(key, *value)
Gets a translation with format arguments.
Parameters:
key: the translation key*value: variadic, used to format the translated text
Returns:
- The formatted translated text
Partial Translation Methods
translate_partial(key: str)
Creates a partially applied translation function.
Parameters:
key: string, the translation key
Returns:
- A partial function for later translation
translate_ctx_partial(key: str, value: List[Any])
Creates a partially applied translation function with format arguments.
Parameters:
key: string, the translation keyvalue: list, the list of format arguments
Returns:
- A partial function for later translation with arguments
File Loading Methods
translate_load(file: Path, ignore=False)
Loads translations from a file.
Parameters:
file: Path, the translation file pathignore: boolean, whether to ignore a missing file error, defaults to False
Returns:
- The loaded translation content
translate_app_info(file_root: Path, filename: str)
Loads the translations for application information.
Parameters:
file_root: Path, the target i18n directoryfilename: string, the file name to translate
Returns:
- The loaded application information translation
Configuration Methods
set_lang(lang: Language = Language.ZH_CN)
Sets the default language.
Parameters:
lang: Language, the language setting, defaults to Simplified Chinese
get_lang()
Gets the current language setting.
Returns:
- The current language setting
set_path(path: str)
Sets the i18n root directory.
Parameters:
path: string, the directory path
Notes
- This class is the core implementation of the i18n feature
- Several translation styles are supported: direct translation, translation with arguments and partial application
- File-level translation loading is provided
- The language and the configuration path can be switched at runtime
- It is implemented with class methods (@classmethod) for convenient static calls
- A cache is used to improve performance
ConfigParser Class
ConfigParser is an abstract base class that defines the basic interface of a configuration file parser. The class provides the standard method definitions for reading and writing configuration files.
__init__(config_path: str)
Initializes a configuration parser instance.
Parameters:
config_path: string, path to the configuration file
Returns: None
read()
Abstract method that reads the configuration file.
Parameters: None
Returns:
- The concrete implementation decides the return type
Note:
- This is an abstract method and must be implemented by a subclass
write()
Abstract method that writes the configuration file.
Parameters: None
Returns:
- The concrete implementation decides the return type
Note:
- This is an abstract method and must be implemented by a subclass
Notes
- This is an abstract base class and cannot be instantiated directly
- Every subclass must implement
read()andwrite() - The class gives parsers for different configuration formats a unified interface
- A subclass can implement the parsing logic for its own format (JSON, YAML, INI and so on)
JsonConfigParser Class
JsonConfigParser is a JSON configuration file parser that inherits from ConfigParser and reads and writes JSON configuration files.
read() -> Any
Reads the content of a JSON configuration file.
Parameters: None
Returns:
- The parsed JSON content (any type)
Implementation details:
- Opens the file with UTF-8 encoding
- Parses the JSON content with
json.load() - Opens and closes the file automatically
write(content: Dict[str, Any]) -> NoReturn
Writes content to a JSON configuration file.
Parameters:
content: dict, the configuration content to write
Returns:
- No return value (NoReturn)
Implementation details:
- Opens the file for writing with the default encoding
- Serializes the content to JSON with
json.dump() - Opens and closes the file automatically
Notes
- Reading uses UTF-8 encoding, so special characters such as Chinese are handled correctly
- The content written must be a dict that can be serialized to JSON
- File operations use
withstatements, so resources are always released - It inherits from the
ConfigParserbase class and implements the standard configuration file interface
YamlConfigParser Class
YamlConfigParser is a YAML configuration file parser that inherits from ConfigParser and reads and writes YAML configuration files.
read() -> Any
Reads the content of a YAML configuration file.
Parameters: None
Returns:
- The parsed YAML content (any type)
Implementation details:
- Opens the file with UTF-8 encoding
- Parses the YAML content safely with
yaml.safe_load() - Opens and closes the file automatically
write(content: Dict[str, Any]) -> NoReturn
Writes content to a YAML configuration file.
Parameters:
content: dict, the configuration content to write
Returns:
- No return value (NoReturn)
Implementation details:
- Opens the file for writing with the default encoding
- Serializes the content to YAML with
yaml.dump() - Opens and closes the file automatically
Notes
- Reading uses UTF-8 encoding, so special characters such as Chinese are handled correctly
- It uses
safe_load()rather thanload(), which gives safer YAML parsing - The content written must be a dict that can be serialized to YAML
- File operations use
withstatements, so resources are always released - It inherits from the
ConfigParserbase class and implements the standard configuration file interface
IniConfigParser Class
IniConfigParser is an INI configuration file parser that inherits from ConfigParser and reads and writes INI configuration files.
read()
Reads the content of an INI configuration file.
Parameters: None
Returns:
- The content of all sections in the configuration file
Implementation details:
- Creates a parser with
configparser.ConfigParser()from the Python standard library - Reads the INI file at the given path
- Returns the
_sectionsattribute, which holds the content of every configuration section
write(content: str)
Writes content to an INI configuration file.
Parameters:
content: string, the configuration content to write
Returns: None
Implementation details:
- Opens the file in write mode
- Writes the string content directly
- Opens and closes the file automatically
Notes
- The read method returns the dict representation of every section in the configuration file
- The write method takes raw string content, so make sure the content is valid INI
- File operations use
withstatements, so resources are always released - It inherits from the
ConfigParserbase class and implements the standard configuration file interface
StringLangValidator
StringLangValidator is a language validator class that inherits from BaseValidator and validates and processes the language field of a form.
__init__(lang="en")
Initializes a language validator instance.
Parameters:
lang: string, the default language code, defaults to "en" (English)
Returns: None
validator(form, field)
Validates the language value of a form field.
Parameters:
form: Form object, the WTForms form instancefield: Field object, the form field instance
Returns:
- The validated language code
Implementation details:
- Gets the field value and uses the default language when it is empty
- Initializes a GI18n instance with the resulting language value
- Returns the final language code
Notes
- The validator is mainly used for form fields related to i18n
- It uses
setting.PROJECT_I18n_PATHas the i18n configuration file path - When the field value is empty, the default language set in the constructor is used
- A GI18n instance is created during validation so the language setting takes effect
StrRangeValidator
StrRangeValidator is a string range validator class that inherits from BaseValidator and validates whether the value of a string field is within the allowed range.
Class Attributes
allows: list, holds the allowed values, defaults to an empty listerr_message: string, the error message template, defaults to an empty string
__init__(allows, message=None)
Initializes a validator instance.
Parameters:
allows: list, the allowed valuesmessage: optional, string, a custom error message, defaults to None
Returns: None
validator(form, field)
Validates whether the form field value is within the allowed range.
Parameters:
form: Form object, the WTForms form instancefield: Field object, the form field instance
Returns: None
Raises:
- Raises a
validators.ValidationErrorexception when the field value is not in the allowed range- if
err_messageis set, the message after i18n translation is used - otherwise the default message format
expected value {allows}is used
- if
Notes
- The validator supports i18n error messages
- The error message can be customized through the constructor
- A ValidationError exception is raised when validation fails
- Useful when a field value has to be limited to a specific set
IntLimitValidator
IntLimitValidator is an integer range validator class that validates whether the value of an integer field in a form is within the given range.
Class Attributes
min: integer, the minimum allowed valuemax: integer, the maximum allowed valueerr_message: string, the error message template, defaults to an empty string
__init__(min=1, max=1000)
Initializes a validator instance.
Parameters:
min: integer, the minimum allowed value, defaults to 1max: integer, the maximum allowed value, defaults to 1000
Returns: None
validator(form, field)
Validates whether the form field value is within the allowed range.
Parameters:
form: Form object, the WTForms form instancefield: Field object, the form field instance
Returns: None
Raises:
- Raises a
validators.ValidationErrorexception when the field value is below the minimum or above the maximum- if
err_messageis set, the message after i18n translation is used, with the minimum and maximum passed as arguments - otherwise the default message format
expected value [min,max]is used
- if
Notes
- The validator supports i18n error messages
- The error message can contain placeholders for the minimum and maximum
- A ValidationError exception is raised when validation fails
- Useful when an integer field value has to be limited to a specific range
- The default range is 1-1000 and can be customized through the constructor
BaseForm Class
BaseForm is a basic form class that inherits from the WTForms Form class and provides the basic language setup.
Class Attributes
lang: StringField, the language field- validated with the
StringLangValidatorvalidator - used to set and validate the language option of the form
- validated with the
Characteristics
- Every form class that inherits from BaseForm automatically includes the language field
- The language field is validated with StringLangValidator, which keeps the language setting valid
- i18n is supported by default
Notes
- This class is a base form class and should be inherited by concrete form classes
- The language validator uses English ("en") as the default language
- Inheriting from it gives every form a consistent language handling mechanism
The following is a summary of the classes and methods documented above:
Class: nan
Placeholder class used to represent a "not a number" (NaN) value.
Methods:
__str__(self): returns the class name as a string.__repr__(self): returns the representation of the class name.
BaseField Class
Base class for form fields, providing the basic field validation features.
Constructor:
__init__(self, validators=None, err_msg="", default=None, valid="", label=""): initializes the field; accepts optional validators, an error message, a default value and validation options.
Methods:
validator(self, value): abstract method that a subclass must implement to validate the field value.get_validators(self): returns the list of validators associated with the field.required(self): checks whether the field has therequiredvalidator.raise_except(self, err_msg, except_type=None): raises an exception of the given type and message.
Field Class
A descriptor class that validates and cleans field values. Inherits from BaseField
Constructor:
__init__(self, validators=None, err_msg="", default=None, valid="", label=""): initializes the field; accepts validators, an error message, a default value and validation options.
Methods:
_get_value(self, value): returns the field value, or the default value when the value isNone.__set__(self, instance, value): sets the field value after validation and cleaning.validator(self, value): validates the field value (a no-op in the base class; a subclass can implement specific validation).clean_data(self, instance, value): cleans the field value by applying the validators.__delete__(self, instance): deletes the field value from the instance.
StringField Class
Field used to handle string values. Inherits from Field
Constructor:
- Inherits from
Fieldand setsexpected_typetostr.
- Inherits from
StringIdentifierField Class
String field specific to identifiers, with length limits and regular expression validation. Inherits from Field
Constructor:
__init__(self, validators=None, err_msg="", max_len=25, min_len=1, valid="", label=""): initializes the field; accepts validators, an error message and length limits.
Methods:
validator(self, value): validates the value with a regular expression and a length check.
StringRegexField Class
Handles string values and validates them with a regular expression. Inherits from StringField
Constructor:
__init__(self, validators=None, err_msg="", regex=None, default=None, valid="", label=""): initializes the field; accepts a regular expression and validation options.
Methods:
validator(self, value): validates the field value with the supplied regular expression.
BooleanField Class
Field used to handle boolean values. Inherits from Field
Constructor:
- Inherits from
Fieldand setsexpected_typetobool.
- Inherits from
IntegerField Class
Field used to handle integer values. Inherits from Field
Constructor:
- Inherits from
Fieldand setsexpected_typetoint.
- Inherits from
ListField Class
Field used to handle list values. Inherits from Field
Constructor:
- Inherits from
Fieldand setsexpected_typetolist.
- Inherits from
DictField Class
Field used to handle dict values. Inherits from Field
Constructor:
- Inherits from
Fieldand setsexpected_typetodict.
- Inherits from
NoValueField Class
Field used to handle "NoValue" (a placeholder for a missing value). Inherits from Field
Constructor:
- Inherits from
Fieldand setsexpected_typetoNoValue.
- Inherits from
RangeField Class
A field class that requires the value to be within an allowed range. Inherits from Field
Constructor:
__init__(self, validators=None, err_msg="", allow=None, default=None, valid="", label=""): initializes the field; supports setting the allowed value range.
Methods:
validator(self, value): validates whether the value is within the allowed range.
StrRangeField Class
A string field whose value must be within the given range. Inherits from RangeField and StringField
IntRangeField Class
An integer field whose value must be within the given range. Inherits from RangeField and IntegerField
PortField Class
A field that handles port values; the value must be within 1 to 65535. Inherits from Field
Constructor:
__init__(self, validators=None, min_value=1, max_value=65535, err_msg="", default=None, valid="", label="")
: initializes the field; supports setting the port range.
Methods:
validator(self, value): validates whether the port value is valid.
LengthLimitField Class
Handles string values and limits their length to the given range. Inherits from StringField
Constructor:
__init__(self, validators=None, min_length=0, max_length=32, err_msg="", default=None, valid="", label="")
: initializes the field; supports setting the minimum and maximum string length.
Methods:
validator(self, value): validates whether the value length is within the given range.
StringRegexLimitField Class
A field that combines a regular expression and length limits for string values. Inherits from StringField
Constructor:
__init__(self, validators=None, min_length=0, max_length=32, err_msg="", default=None, regex=None, valid="", label="")
: initializes the field; supports a regular expression plus minimum and maximum length.Methods:
validator(self, value): validates the value length and the regular expression.
IntegerLimitField Class
Handles integer values and limits them to the given minimum and maximum range. Inherits from IntegerField
Constructor:
__init__(self, validators=None, min_value=0, max_value=32, err_msg="", default=None, valid="", label="")
: initializes the field; supports setting the minimum and maximum values.
Methods:
validator(self, value): validates whether the integer value is within the given range.
StringValueLimitField Class
Handles string values and limits them to the given range. Inherits from StringField
Constructor:
__init__(self, validators=None, min_value=nan, max_value=nan, err_msg="", default=None, valid="", label="")
: initializes the field; supports setting the minimum and maximum values.
Methods:
validator(self, value): validates whether the string value is within the given range.
StringLengthLimitField Class
A field that combines string length limits. Inherits from LengthLimitField
StringRangField Class
A field that combines string range limits. Inherits from StrRangeField
IntegerRangeField Class
A field that combines integer range limits. Inherits from IntRangeField
GLogger class
GLogger is a global log management class built on the loguru library that provides a unified logging interface. It uses the singleton pattern so log configuration stays consistent across the whole application.
Logging features
- Singleton pattern: one global logger instance
- Multiple levels: supports DEBUG, INFO, WARNING, ERROR and CRITICAL
- Multiple sinks: console, file, remote and more
- Formatted output: supports custom log formats
- Asynchronous writes: high-performance asynchronous log writing
- Automatic rotation: rotates log files by time or size
Log levels
| Level | Value | Purpose |
|---|---|---|
| DEBUG | 10 | Debug information, detailed program execution details |
| INFO | 20 | General information, normal program operation |
| WARNING | 30 | Warnings, possible problems that do not affect operation |
| ERROR | 40 | Errors, the program hit an error but can keep running |
| CRITICAL | 50 | Critical errors, the program may fail to keep running |
__init__(config: Optional[Dict[str, Any]] = None)
Initializes a GLogger instance. Because of the singleton pattern, initializing more than once returns the same instance.
Parameters:
config: optional dictionary with the logging configuration
Returns: nothing
Example:
from simplejrpc import GLogger
# Use the default configuration
logger = GLogger()
# Use a custom configuration
log_config = {
"level": "INFO",
"format": "{time:YYYY-MM-DD HH:mm:ss} | {level} | {name}:{function}:{line} - {message}",
"handlers": [
{
"sink": "logs/app.log",
"rotation": "1 day",
"retention": "7 days",
"compression": "zip"
},
{
"sink": "sys.stdout",
"colorize": True
}
]
}
logger = GLogger(config=log_config)
# Verify the singleton
logger1 = GLogger()
logger2 = GLogger()
print(logger1 is logger2) # Trueget_instance()
Gets the GLogger singleton instance. If no instance exists yet, a new one is created.
Parameters: none
Returns:
- The GLogger instance
Example:
from simplejrpc import GLogger
# Get the logger instance in any module
logger = GLogger.get_instance()
# Use the same logger instance in different modules
# module_a.py
def process_data():
logger = GLogger.get_instance()
logger.info("开始处理数据")
try:
# Processing logic
logger.debug("数据处理中...")
result = "处理完成"
logger.info(f"数据处理成功: {result}")
return result
except Exception as e:
logger.error(f"数据处理失败: {e}")
raise
# module_b.py
def save_result(data):
logger = GLogger.get_instance()
logger.info(f"保存结果: {data}")
# Save logic
logger.info("结果保存成功")debug(message: str)
Logs a debug-level message. Use it for detailed program execution information, typically during development and debugging.
Parameters:
message: string, the log message
Returns: nothing
Example:
from simplejrpc import GLogger
logger = GLogger.get_instance()
# Log debug information
logger.debug("进入函数 calculate_total")
logger.debug(f"参数值: price={100}, quantity={5}")
def calculate_total(price, quantity):
logger.debug(f"开始计算总价: price={price}, quantity={quantity}")
total = price * quantity
logger.debug(f"计算结果: {total}")
return total
result = calculate_total(100, 5)
logger.debug(f"函数返回值: {result}")info(message: str)
Logs an info-level message. Use it to record important information about normal program operation.
Parameters:
message: string, the log message
Returns: nothing
Example:
from simplejrpc import GLogger
logger = GLogger.get_instance()
# Log application startup information
logger.info("应用程序启动")
logger.info("加载配置文件: config.yaml")
logger.info("连接数据库成功")
# Log business operations
def create_user(username, email):
logger.info(f"创建新用户: {username}")
# User creation logic
user_id = 12345
logger.info(f"用户创建成功: ID={user_id}, 用户名={username}")
return user_id
# Log system status
logger.info("系统运行正常")
logger.info("当前活跃连接数: 25")warning(message: str)
Logs a warning-level message. Use it to record situations that may signal a problem without stopping the program.
Parameters:
message: string, the log message
Returns: nothing
Example:
from simplejrpc import GLogger
logger = GLogger.get_instance()
# Log performance warnings
logger.warning("数据库查询耗时过长: 5.2秒")
logger.warning("内存使用率达到 85%")
# Log configuration warnings
def load_config(config_path):
if not os.path.exists(config_path):
logger.warning(f"配置文件不存在,使用默认配置: {config_path}")
return default_config
return load_from_file(config_path)
# Log business warnings
def process_payment(amount):
if amount > 10000:
logger.warning(f"大额支付警告: {amount} 元")
# Payment processing logicerror(message: str)
Logs an error-level message. Use it to record errors that occur while the program can still continue running.
Parameters:
message: string, the log message
Returns: nothing
Example:
from simplejrpc import GLogger
logger = GLogger.get_instance()
# Log exceptions
def divide_numbers(a, b):
try:
result = a / b
return result
except ZeroDivisionError as e:
logger.error(f"除零错误: {a} / {b} - {str(e)}")
return None
except Exception as e:
logger.error(f"计算错误: {str(e)}")
return None
# Log network errors
def fetch_data(url):
try:
response = requests.get(url, timeout=5)
return response.json()
except requests.RequestException as e:
logger.error(f"网络请求失败: {url} - {str(e)}")
return None
# Log database errors
def save_user(user_data):
try:
# Save user data
db.save(user_data)
logger.info("用户数据保存成功")
except DatabaseError as e:
logger.error(f"数据库保存失败: {str(e)}")
raisecritical(message: str)
Logs a critical-level message. Use it for severe errors that may prevent the program from continuing.
Parameters:
message: string, the log message
Returns: nothing
Example:
from simplejrpc import GLogger
import sys
logger = GLogger.get_instance()
# Log critical system-level errors
def initialize_database():
try:
# Initialize the database connection
db.connect()
except Exception as e:
logger.critical(f"数据库初始化失败,程序无法启动: {str(e)}")
sys.exit(1)
# Log resource exhaustion
def check_system_resources():
memory_usage = get_memory_usage()
if memory_usage > 95:
logger.critical(f"内存使用率过高: {memory_usage}%,系统可能崩溃")
disk_usage = get_disk_usage()
if disk_usage > 98:
logger.critical(f"磁盘空间不足: {disk_usage}%,无法继续写入")
# Log security issues
def validate_security():
if detect_security_breach():
logger.critical("检测到安全漏洞,立即停止服务")
shutdown_service()configure(config: Dict[str, Any])
Configures the logging system. You can update the logging configuration dynamically at runtime.
Parameters:
config: dictionary with the logging configuration
Returns: nothing
Configuration options:
level: log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)format: log format stringhandlers: list of output handlersrotation: log rotation settingsretention: log retention settingscompression: compression settings
Example:
from simplejrpc import GLogger
logger = GLogger.get_instance()
# Basic configuration
basic_config = {
"level": "INFO",
"format": "{time} | {level} | {message}"
}
logger.configure(basic_config)
# Advanced configuration
advanced_config = {
"level": "DEBUG",
"format": "{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} - {message}",
"handlers": [
{
"sink": "logs/app_{time:YYYY-MM-DD}.log",
"rotation": "00:00", # Rotate at midnight every day
"retention": "30 days", # Keep for 30 days
"compression": "zip", # Compress old logs
"level": "INFO"
},
{
"sink": "logs/error.log",
"level": "ERROR",
"rotation": "10 MB", # Rotate by size
"retention": "1 week"
},
{
"sink": "sys.stdout",
"colorize": True,
"level": "DEBUG"
}
]
}
logger.configure(advanced_config)
# Production configuration
production_config = {
"level": "WARNING",
"format": "{time:YYYY-MM-DD HH:mm:ss} | {level} | {extra[request_id]} | {message}",
"handlers": [
{
"sink": "/var/log/myapp/app.log",
"rotation": "1 day",
"retention": "90 days",
"compression": "gz"
},
{
"sink": "syslog", # System log
"level": "ERROR"
}
]
}
logger.configure(production_config)Notes
- Singleton pattern: GLogger uses the singleton pattern so the global log configuration stays consistent
- Thread safety: built on the loguru library, it supports multithreaded environments natively
- Performance: asynchronous log writing never blocks the main thread
- Automatic rotation: rotates log files automatically by time, size and other conditions
- Formatting: rich formatting options including time, level and location
- Filters: configuration can filter logs and route them by level
- Compressed storage: automatically compresses historical log files to save space
Best practices
Use log levels sensibly:
- DEBUG: during development and debugging
- INFO: important business flows
- WARNING: potential problems
- ERROR: errors the program can continue from
- CRITICAL: critical errors
Structured logs: use a consistent log format so later analysis is easier
Avoid sensitive information: never log passwords, keys or other sensitive data
Reasonable log rotation: set a rotation strategy that matches the size of your app
Monitor log files: check log file size and disk usage regularly
Development best practices
Error handling
from simplejrpc import ServerApplication, RPCException, GLogger
app = ServerApplication("/tmp/rpc.sock")
logger = GLogger.get_instance()
@app.route("safe_divide")
def safe_divide(a: float, b: float):
try:
if b == 0:
raise RPCException("除数不能为零", code=-32001)
result = a / b
logger.info(f"计算成功: {a} / {b} = {result}")
return result
except Exception as e:
logger.error(f"计算错误: {str(e)}")
raise RPCException(f"计算失败: {str(e)}", code=-32002)Configuration management
from simplejrpc import ServerApplication, GConfig
# Unified configuration management
config = GConfig(config_path="config.yaml")
app = ServerApplication(
socket_path=config.get("server.socket_path", "/tmp/rpc.sock"),
config=config
)
@app.route("get_config")
def get_config(key: str):
return config.get(key, "配置不存在")Using middleware
from simplejrpc import ServerApplication
import time
app = ServerApplication("/tmp/rpc.sock")
# Performance monitoring middleware
def performance_middleware(request, call_next):
start_time = time.time()
response = call_next(request)
duration = time.time() - start_time
if duration > 1.0: # Warn about requests slower than one second
logger.warning(f"慢请求: {request.method} 耗时 {duration:.3f}s")
return response
app.add_middleware(performance_middleware)Form validation
from simplejrpc import ServerApplication, BaseForm
from simplejrpc.fields import StringField, IntegerField, BooleanField
class UserCreateForm(BaseForm):
username = StringField(min_length=3, max_length=20)
age = IntegerField(min_value=1, max_value=120)
is_active = BooleanField(default=True)
@app.route("create_user", form=UserCreateForm)
def create_user(data: UserCreateForm):
# The data has already been validated
return {
"id": 123,
"username": data.username,
"age": data.age,
"is_active": data.is_active
}Summary
The simplejrpc module provides a complete JSON-RPC server development solution. Its main features are:
Core features
- ServerApplication: the core RPC server class, with route registration, middleware and configuration management
- Configuration system: Settings and GConfig provide flexible configuration management
- Logging system: GLogger, powerful logging based on loguru
- Form validation: a wide range of field types and validators
- Exception handling: a complete RPC exception hierarchy
- Internationalization: T and GI18n provide multilingual support
- Transport layer: high-performance Unix domain socket communication
Advantages
- Easy to use: a clean API design for a quick start
- High performance: low-latency communication over Unix domain sockets
- Extensible: the middleware system supports feature extensions
- Type safe: full type annotation support
- Production ready: complete logging, configuration and exception handling
- Internationalization: multilingual support built in
