litefs package

Build a web server framework using Python. Litefs was developed to implement a server framework that can quickly, securely, and flexibly build Web projects. Litefs is a high-performance HTTP server. Litefs has the characteristics of high stability, rich functions, and low system consumption.

Author: leafcoder Email: leafcoder@gmail.com

Copyright (c) 2020, Leafcoder. License: MIT (see LICENSE for details)

class litefs.CacheBackend[源代码]

基类:object

缓存后端类型

DATABASE = 'database'
MEMCACHE = 'memcache'
MEMORY = 'memory'
REDIS = 'redis'
TREE = 'tree'
class litefs.CacheFactory[源代码]

基类:object

缓存工厂

根据配置创建不同类型的缓存实例

static create_cache(backend: str = 'memory', **kwargs) MemoryCache | TreeCache | RedisCache | DatabaseCache | MemcacheCache[源代码]

创建缓存实例

参数:
  • backend -- 缓存后端类型(memory, tree, redis, database, memcache)

  • **kwargs -- 缓存配置参数

返回:

缓存实例

抛出:
  • ValueError -- 不支持的缓存后端

  • ImportError -- Redis 或 Memcache 包未安装

static create_from_config(config) MemoryCache | TreeCache | RedisCache | DatabaseCache | MemcacheCache[源代码]

从配置对象创建缓存实例

参数:

config -- 配置对象,应包含 cache_backend 和相关配置

返回:

缓存实例

class litefs.CacheManager[源代码]

基类:object

全局缓存管理器(单例模式)

确保缓存对象在应用生命周期内常驻内存,不会因为 Litefs 实例的 创建和销毁而丢失数据。

使用示例:

# 获取缓存实例(自动创建) cache = CacheManager.get_cache()

# 获取指定类型的缓存 session_cache = CacheManager.get_cache(

backend='memory', max_size=1000000, cache_key='sessions'

)

# 重置缓存(谨慎使用) CacheManager.reset_cache()

classmethod get_cache(backend: str = 'tree', cache_key: str | None = None, **kwargs) MemoryCache | TreeCache | RedisCache | DatabaseCache | MemcacheCache[源代码]

获取缓存实例(单例模式)

如果缓存实例不存在,则自动创建。同一 cache_key 的缓存实例 在整个应用生命周期内保持唯一。

参数:
  • backend -- 缓存后端类型

  • cache_key -- 缓存实例标识,None 使用默认缓存

  • **kwargs -- 缓存配置参数

返回:

缓存实例

classmethod get_file_cache(**kwargs)[源代码]

获取文件缓存实例

参数:

**kwargs -- 配置参数,支持 clean_period, expiration_time

返回:

TreeCache 实例

classmethod get_session_cache(**kwargs)[源代码]

获取会话缓存实例

参数:

**kwargs -- 配置参数,支持 max_size

返回:

MemoryCache 实例

classmethod has_cache(cache_key: str) bool[源代码]

检查缓存实例是否存在

参数:

cache_key -- 缓存标识

返回:

是否存在

classmethod list_caches() list[源代码]

获取所有缓存标识列表

返回:

缓存标识列表

classmethod reset_cache(cache_key: str | None = None) None[源代码]

重置缓存实例

谨慎使用!重置后缓存数据将丢失。

参数:

cache_key -- 要重置的缓存标识,None 重置所有缓存

class litefs.ChoiceValidator(choices: List[Any], message: str | None = None)[源代码]

基类:Validator

选择验证器

validate(value: Any, field_name: str | None = None) Any[源代码]

验证值

参数:
  • value -- 要验证的值

  • field_name -- 字段名称

返回:

验证后的值

抛出:

ValidationError -- 验证失败

class litefs.Config(config_file: str | None = None, **kwargs)[源代码]

基类:object

配置管理类

支持多种配置来源和分层管理: 1. 默认配置(内置) 2. 环境配置(如 config.production.yaml) 3. 本地配置(如 config.local.yaml) 4. 环境变量 5. 代码中的配置

配置优先级(从高到低): 代码配置 > 环境变量 > 本地配置 > 环境配置 > 默认值

DEFAULT_CONFIG = {'cache_backend': 'tree', 'cache_clean_period': 60, 'cache_expiration_time': 3600, 'cache_max_size': 10000, 'config_encrypted_keys': [], 'config_env': None, 'config_file': None, 'config_secret_key': None, 'database_cache_table': 'cache', 'database_session_table': 'sessions', 'database_url': None, 'debug': False, 'default_page': 'index,index.html', 'error_pages_dir': None, 'file_cache_clean_period': 60, 'file_cache_expiration_time': 3600, 'host': 'localhost', 'listen': 1024, 'log': './default.log', 'max_request_size': 10485760, 'max_upload_size': 52428800, 'memcache_key_prefix': 'litefs:', 'memcache_servers': 'localhost:11211', 'memcache_session_key_prefix': 'litefs:session:', 'port': 9090, 'redis_db': 0, 'redis_host': 'localhost', 'redis_key_prefix': 'litefs:', 'redis_password': None, 'redis_port': 6379, 'redis_session_key_prefix': 'litefs:session:', 'session_backend': 'memory', 'session_expiration_time': 3600, 'session_http_only': True, 'session_max_size': 1000000, 'session_name': 'litefs.sid', 'session_same_site': 'Lax', 'session_secure': False}
ENV_PREFIX = 'LITEFS_'
decrypt_config(encrypted_value: str) Any[源代码]

解密配置值

参数:

encrypted_value -- 加密后的字符串

返回:

解密后的值

encrypt_config(key: str, value: Any) str[源代码]

加密配置值

参数:
  • key -- 配置键

  • value -- 配置值

返回:

加密后的字符串

get(key: str, default: Any | None = None) Any[源代码]

获取配置项

参数:
  • key -- 配置键

  • default -- 默认值

返回:

配置值

items() List[tuple][源代码]

获取所有配置项

keys() List[str][源代码]

获取所有配置键

set(key: str, value: Any)[源代码]

设置配置项

参数:
  • key -- 配置键

  • value -- 配置值

to_dict() Dict[str, Any][源代码]

转换为字典

返回:

配置字典

update(**kwargs)[源代码]

批量更新配置

参数:

**kwargs -- 配置项

values() List[Any][源代码]

获取所有配置值

class litefs.EmailValidator(message: str = '请输入有效的邮箱地址')[源代码]

基类:Validator

邮箱验证器

validate(value: Any, field_name: str | None = None) Any[源代码]

验证值

参数:
  • value -- 要验证的值

  • field_name -- 字段名称

返回:

验证后的值

抛出:

ValidationError -- 验证失败

class litefs.EnhancedRequestHandler(request_handler)[源代码]

基类:object

增强的请求处理器

提供分离的 query 和 post 参数,以及表单验证功能

property body: str

获取请求体

返回:

请求体字符串

property config

获取配置对象

返回:

配置对象

property content_length: int

获取内容长度

返回:

内容长度

property content_type: str | None

获取内容类型

返回:

内容类型

property cookie

获取 Cookie

返回:

Cookie 对象

property environ: Dict[str, Any]

获取环境变量

返回:

环境变量字典

property files: Dict[str, Any]

获取上传的文件

返回:

文件字典

get_file(key: str, default: Any | None = None) Any[源代码]

获取单个上传文件

参数:
  • key -- 文件字段名

  • default -- 默认值

返回:

文件对象

get_post_param(key: str, default: Any | None = None) Any[源代码]

获取单个 POST 参数

参数:
  • key -- 参数名

  • default -- 默认值

返回:

参数值

get_query_param(key: str, default: Any | None = None) Any[源代码]

获取单个查询参数

参数:
  • key -- 参数名

  • default -- 默认值

返回:

参数值

property json: Dict[str, Any]

获取 JSON 请求体

返回:

JSON 数据字典

property path_info: str

获取路径信息

返回:

路径信息

property post: Dict[str, Any]

获取 POST 请求体参数

返回:

POST 参数字典

property query: Dict[str, Any]

获取 URL 查询参数

返回:

查询参数字典

property query_string: str

获取查询字符串

返回:

查询字符串

property referer: str | None

获取来源页面

返回:

来源页面 URL

property request_method: str

获取请求方法

返回:

请求方法(GET, POST, PUT, DELETE 等)

property request_uri: str

获取请求 URI

返回:

请求 URI

property session

获取会话对象

返回:

会话对象

property session_id: str | None

获取会话 ID

返回:

会话 ID

设置 Cookie

参数:
  • key -- Cookie 名称

  • value -- Cookie 值

  • **kwargs -- 其他 Cookie 参数

set_form_validator(validator: FormValidator)[源代码]

设置表单验证器

参数:

validator -- 表单验证器实例

start_response(status_code: int = 200, headers=None)[源代码]

开始响应

参数:
  • status_code -- HTTP 状态码

  • headers -- 响应头列表

validate_all(query_rules: Dict[str, List] | None = None, post_rules: Dict[str, List] | None = None, file_rules: Dict[str, List] | None = None) Tuple[bool, Dict[str, Dict[str, List[str]]]][源代码]

验证所有参数

参数:
  • query_rules -- 查询参数验证规则

  • post_rules -- POST 参数验证规则

  • file_rules -- 文件验证规则

返回:

错误字典})

返回类型:

(是否验证成功, {参数类型

validate_files(rules: Dict[str, List]) Tuple[bool, Dict[str, List[str]]][源代码]

验证上传文件

参数:

rules -- 验证规则字典 {字段名: [验证器列表]}

返回:

(是否验证成功, 错误字典)

validate_post(rules: Dict[str, List]) Tuple[bool, Dict[str, List[str]]][源代码]

验证 POST 参数

参数:

rules -- 验证规则字典 {字段名: [验证器列表]}

返回:

(是否验证成功, 错误字典)

validate_query(rules: Dict[str, List]) Tuple[bool, Dict[str, List[str]]][源代码]

验证查询参数

参数:

rules -- 验证规则字典 {字段名: [验证器列表]}

返回:

(是否验证成功, 错误字典)

class litefs.ErrorPageRenderer(custom_error_dir: str | None = None)[源代码]

基类:object

错误页面渲染器

支持默认错误页面和自定义错误页面

DEFAULT_ERROR_TEMPLATES = {400: '\n<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n    <meta charset="UTF-8">\n    <meta name="viewport" content="width=device-width, initial-scale=1.0">\n    <title>400 - 错误的请求</title>\n    <style>\n        * {\n            margin: 0;\n            padding: 0;\n            box-sizing: border-box;\n        }\n        body {\n            font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif;\n            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n            min-height: 100vh;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            padding: 20px;\n        }\n        .error-container {\n            background: white;\n            border-radius: 20px;\n            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n            padding: 60px 40px;\n            text-align: center;\n            max-width: 500px;\n            width: 100%;\n        }\n        .error-code {\n            font-size: 120px;\n            font-weight: bold;\n            color: #667eea;\n            line-height: 1;\n            margin-bottom: 20px;\n        }\n        .error-title {\n            font-size: 28px;\n            color: #333;\n            margin-bottom: 15px;\n        }\n        .error-message {\n            font-size: 16px;\n            color: #666;\n            line-height: 1.6;\n            margin-bottom: 30px;\n        }\n        .error-detail {\n            background: #f7f7f7;\n            padding: 15px;\n            border-radius: 8px;\n            font-size: 14px;\n            color: #888;\n            margin-bottom: 30px;\n        }\n        .btn-home {\n            display: inline-block;\n            padding: 12px 30px;\n            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n            color: white;\n            text-decoration: none;\n            border-radius: 25px;\n            font-weight: 500;\n            transition: transform 0.2s, box-shadow 0.2s;\n        }\n        .btn-home:hover {\n            transform: translateY(-2px);\n            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);\n        }\n    </style>\n</head>\n<body>\n    <div class="error-container">\n        <div class="error-code">400</div>\n        <h1 class="error-title">错误的请求</h1>\n        <p class="error-message">\n            服务器无法理解您的请求。请检查您的请求格式是否正确。\n        </p>\n        <div class="error-detail">\n            错误代码: 400 Bad Request<br>\n            说明: 客户端发送的请求有语法错误\n        </div>\n        <a href="/" class="btn-home">返回首页</a>\n    </div>\n</body>\n</html>\n        ', 403: '\n<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n    <meta charset="UTF-8">\n    <meta name="viewport" content="width=device-width, initial-scale=1.0">\n    <title>403 - 禁止访问</title>\n    <style>\n        * {\n            margin: 0;\n            padding: 0;\n            box-sizing: border-box;\n        }\n        body {\n            font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif;\n            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);\n            min-height: 100vh;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            padding: 20px;\n        }\n        .error-container {\n            background: white;\n            border-radius: 20px;\n            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n            padding: 60px 40px;\n            text-align: center;\n            max-width: 500px;\n            width: 100%;\n        }\n        .error-icon {\n            font-size: 80px;\n            margin-bottom: 20px;\n        }\n        .error-code {\n            font-size: 120px;\n            font-weight: bold;\n            color: #f5576c;\n            line-height: 1;\n            margin-bottom: 20px;\n        }\n        .error-title {\n            font-size: 28px;\n            color: #333;\n            margin-bottom: 15px;\n        }\n        .error-message {\n            font-size: 16px;\n            color: #666;\n            line-height: 1.6;\n            margin-bottom: 30px;\n        }\n        .error-detail {\n            background: #f7f7f7;\n            padding: 15px;\n            border-radius: 8px;\n            font-size: 14px;\n            color: #888;\n            margin-bottom: 30px;\n        }\n        .btn-home {\n            display: inline-block;\n            padding: 12px 30px;\n            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);\n            color: white;\n            text-decoration: none;\n            border-radius: 25px;\n            font-weight: 500;\n            transition: transform 0.2s, box-shadow 0.2s;\n        }\n        .btn-home:hover {\n            transform: translateY(-2px);\n            box-shadow: 0 5px 15px rgba(245, 87, 108, 0.4);\n        }\n    </style>\n</head>\n<body>\n    <div class="error-container">\n        <div class="error-icon">🔒</div>\n        <div class="error-code">403</div>\n        <h1 class="error-title">禁止访问</h1>\n        <p class="error-message">\n            您没有权限访问此页面。如果您认为这是一个错误,请联系管理员。\n        </p>\n        <div class="error-detail">\n            错误代码: 403 Forbidden<br>\n            说明: 服务器拒绝执行此请求\n        </div>\n        <a href="/" class="btn-home">返回首页</a>\n    </div>\n</body>\n</html>\n        ', 404: '\n<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n    <meta charset="UTF-8">\n    <meta name="viewport" content="width=device-width, initial-scale=1.0">\n    <title>404 - 页面未找到</title>\n    <style>\n        * {\n            margin: 0;\n            padding: 0;\n            box-sizing: border-box;\n        }\n        body {\n            font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif;\n            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);\n            min-height: 100vh;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            padding: 20px;\n        }\n        .error-container {\n            background: white;\n            border-radius: 20px;\n            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n            padding: 60px 40px;\n            text-align: center;\n            max-width: 500px;\n            width: 100%;\n        }\n        .error-icon {\n            font-size: 80px;\n            margin-bottom: 20px;\n        }\n        .error-code {\n            font-size: 120px;\n            font-weight: bold;\n            color: #4facfe;\n            line-height: 1;\n            margin-bottom: 20px;\n        }\n        .error-title {\n            font-size: 28px;\n            color: #333;\n            margin-bottom: 15px;\n        }\n        .error-message {\n            font-size: 16px;\n            color: #666;\n            line-height: 1.6;\n            margin-bottom: 30px;\n        }\n        .error-detail {\n            background: #f7f7f7;\n            padding: 15px;\n            border-radius: 8px;\n            font-size: 14px;\n            color: #888;\n            margin-bottom: 30px;\n        }\n        .btn-home {\n            display: inline-block;\n            padding: 12px 30px;\n            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);\n            color: white;\n            text-decoration: none;\n            border-radius: 25px;\n            font-weight: 500;\n            transition: transform 0.2s, box-shadow 0.2s;\n        }\n        .btn-home:hover {\n            transform: translateY(-2px);\n            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);\n        }\n    </style>\n</head>\n<body>\n    <div class="error-container">\n        <div class="error-icon">🔍</div>\n        <div class="error-code">404</div>\n        <h1 class="error-title">页面未找到</h1>\n        <p class="error-message">\n            抱歉,您访问的页面不存在或已被删除。\n        </p>\n        <div class="error-detail">\n            错误代码: 404 Not Found<br>\n            说明: 服务器无法找到请求的资源\n        </div>\n        <a href="/" class="btn-home">返回首页</a>\n    </div>\n</body>\n</html>\n        ', 500: '\n<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n    <meta charset="UTF-8">\n    <meta name="viewport" content="width=device-width, initial-scale=1.0">\n    <title>500 - 服务器内部错误</title>\n    <style>\n        * {\n            margin: 0;\n            padding: 0;\n            box-sizing: border-box;\n        }\n        body {\n            font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif;\n            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);\n            min-height: 100vh;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            padding: 20px;\n        }\n        .error-container {\n            background: white;\n            border-radius: 20px;\n            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n            padding: 60px 40px;\n            text-align: center;\n            max-width: 500px;\n            width: 100%;\n        }\n        .error-icon {\n            font-size: 80px;\n            margin-bottom: 20px;\n        }\n        .error-code {\n            font-size: 120px;\n            font-weight: bold;\n            color: #fa709a;\n            line-height: 1;\n            margin-bottom: 20px;\n        }\n        .error-title {\n            font-size: 28px;\n            color: #333;\n            margin-bottom: 15px;\n        }\n        .error-message {\n            font-size: 16px;\n            color: #666;\n            line-height: 1.6;\n            margin-bottom: 30px;\n        }\n        .error-detail {\n            background: #f7f7f7;\n            padding: 15px;\n            border-radius: 8px;\n            font-size: 14px;\n            color: #888;\n            margin-bottom: 30px;\n        }\n        .btn-home {\n            display: inline-block;\n            padding: 12px 30px;\n            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);\n            color: white;\n            text-decoration: none;\n            border-radius: 25px;\n            font-weight: 500;\n            transition: transform 0.2s, box-shadow 0.2s;\n        }\n        .btn-home:hover {\n            transform: translateY(-2px);\n            box-shadow: 0 5px 15px rgba(250, 112, 154, 0.4);\n        }\n    </style>\n</head>\n<body>\n    <div class="error-container">\n        <div class="error-icon">⚠️</div>\n        <div class="error-code">500</div>\n        <h1 class="error-title">服务器内部错误</h1>\n        <p class="error-message">\n            服务器遇到了一个意外情况,无法完成您的请求。请稍后再试。\n        </p>\n        <div class="error-detail">\n            错误代码: 500 Internal Server Error<br>\n            说明: 服务器遇到意外情况\n        </div>\n        <a href="/" class="btn-home">返回首页</a>\n    </div>\n</body>\n</html>\n        ', 502: '\n<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n    <meta charset="UTF-8">\n    <meta name="viewport" content="width=device-width, initial-scale=1.0">\n    <title>502 - 网关错误</title>\n    <style>\n        * {\n            margin: 0;\n            padding: 0;\n            box-sizing: border-box;\n        }\n        body {\n            font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif;\n            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);\n            min-height: 100vh;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            padding: 20px;\n        }\n        .error-container {\n            background: white;\n            border-radius: 20px;\n            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n            padding: 60px 40px;\n            text-align: center;\n            max-width: 500px;\n            width: 100%;\n        }\n        .error-icon {\n            font-size: 80px;\n            margin-bottom: 20px;\n        }\n        .error-code {\n            font-size: 120px;\n            font-weight: bold;\n            color: #a8edea;\n            line-height: 1;\n            margin-bottom: 20px;\n        }\n        .error-title {\n            font-size: 28px;\n            color: #333;\n            margin-bottom: 15px;\n        }\n        .error-message {\n            font-size: 16px;\n            color: #666;\n            line-height: 1.6;\n            margin-bottom: 30px;\n        }\n        .error-detail {\n            background: #f7f7f7;\n            padding: 15px;\n            border-radius: 8px;\n            font-size: 14px;\n            color: #888;\n            margin-bottom: 30px;\n        }\n        .btn-home {\n            display: inline-block;\n            padding: 12px 30px;\n            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);\n            color: white;\n            text-decoration: none;\n            border-radius: 25px;\n            font-weight: 500;\n            transition: transform 0.2s, box-shadow 0.2s;\n        }\n        .btn-home:hover {\n            transform: translateY(-2px);\n            box-shadow: 0 5px 15px rgba(168, 237, 234, 0.4);\n        }\n    </style>\n</head>\n<body>\n    <div class="error-container">\n        <div class="error-icon">🌐</div>\n        <div class="error-code">502</div>\n        <h1 class="error-title">网关错误</h1>\n        <p class="error-message">\n            服务器作为网关或代理,从上游服务器收到了无效的响应。\n        </p>\n        <div class="error-detail">\n            错误代码: 502 Bad Gateway<br>\n            说明: 上游服务器响应无效\n        </div>\n        <a href="/" class="btn-home">返回首页</a>\n    </div>\n</body>\n</html>\n        ', 503: '\n<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n    <meta charset="UTF-8">\n    <meta name="viewport" content="width=device-width, initial-scale=1.0">\n    <title>503 - 服务不可用</title>\n    <style>\n        * {\n            margin: 0;\n            padding: 0;\n            box-sizing: border-box;\n        }\n        body {\n            font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif;\n            background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);\n            min-height: 100vh;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            padding: 20px;\n        }\n        .error-container {\n            background: white;\n            border-radius: 20px;\n            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n            padding: 60px 40px;\n            text-align: center;\n            max-width: 500px;\n            width: 100%;\n        }\n        .error-icon {\n            font-size: 80px;\n            margin-bottom: 20px;\n        }\n        .error-code {\n            font-size: 120px;\n            font-weight: bold;\n            color: #ff9a9e;\n            line-height: 1;\n            margin-bottom: 20px;\n        }\n        .error-title {\n            font-size: 28px;\n            color: #333;\n            margin-bottom: 15px;\n        }\n        .error-message {\n            font-size: 16px;\n            color: #666;\n            line-height: 1.6;\n            margin-bottom: 30px;\n        }\n        .error-detail {\n            background: #f7f7f7;\n            padding: 15px;\n            border-radius: 8px;\n            font-size: 14px;\n            color: #888;\n            margin-bottom: 30px;\n        }\n        .btn-home {\n            display: inline-block;\n            padding: 12px 30px;\n            background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);\n            color: white;\n            text-decoration: none;\n            border-radius: 25px;\n            font-weight: 500;\n            transition: transform 0.2s, box-shadow 0.2s;\n        }\n        .btn-home:hover {\n            transform: translateY(-2px);\n            box-shadow: 0 5px 15px rgba(255, 154, 158, 0.4);\n        }\n    </style>\n</head>\n<body>\n    <div class="error-container">\n        <div class="error-icon">🔧</div>\n        <div class="error-code">503</div>\n        <h1 class="error-title">服务不可用</h1>\n        <p class="error-message">\n            服务器当前无法处理请求,可能正在进行维护或过载。请稍后再试。\n        </p>\n        <div class="error-detail">\n            错误代码: 503 Service Unavailable<br>\n            说明: 服务器暂时无法处理请求\n        </div>\n        <a href="/" class="btn-home">返回首页</a>\n    </div>\n</body>\n</html>\n        ', 504: '\n<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n    <meta charset="UTF-8">\n    <meta name="viewport" content="width=device-width, initial-scale=1.0">\n    <title>504 - 网关超时</title>\n    <style>\n        * {\n            margin: 0;\n            padding: 0;\n            box-sizing: border-box;\n        }\n        body {\n            font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif;\n            background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);\n            min-height: 100vh;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            padding: 20px;\n        }\n        .error-container {\n            background: white;\n            border-radius: 20px;\n            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n            padding: 60px 40px;\n            text-align: center;\n            max-width: 500px;\n            width: 100%;\n        }\n        .error-icon {\n            font-size: 80px;\n            margin-bottom: 20px;\n        }\n        .error-code {\n            font-size: 120px;\n            font-weight: bold;\n            color: #fbc2eb;\n            line-height: 1;\n            margin-bottom: 20px;\n        }\n        .error-title {\n            font-size: 28px;\n            color: #333;\n            margin-bottom: 15px;\n        }\n        .error-message {\n            font-size: 16px;\n            color: #666;\n            line-height: 1.6;\n            margin-bottom: 30px;\n        }\n        .error-detail {\n            background: #f7f7f7;\n            padding: 15px;\n            border-radius: 8px;\n            font-size: 14px;\n            color: #888;\n            margin-bottom: 30px;\n        }\n        .btn-home {\n            display: inline-block;\n            padding: 12px 30px;\n            background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);\n            color: white;\n            text-decoration: none;\n            border-radius: 25px;\n            font-weight: 500;\n            transition: transform 0.2s, box-shadow 0.2s;\n        }\n        .btn-home:hover {\n            transform: translateY(-2px);\n            box-shadow: 0 5px 15px rgba(251, 194, 235, 0.4);\n        }\n    </style>\n</head>\n<body>\n    <div class="error-container">\n        <div class="error-icon">⏱️</div>\n        <div class="error-code">504</div>\n        <h1 class="error-title">网关超时</h1>\n        <p class="error-message">\n            服务器作为网关或代理,未及时从上游服务器收到响应。\n        </p>\n        <div class="error-detail">\n            错误代码: 504 Gateway Timeout<br>\n            说明: 上游服务器响应超时\n        </div>\n        <a href="/" class="btn-home">返回首页</a>\n    </div>\n</body>\n</html>\n        '}
get_error_page(status_code: int, message: str | None = None, detail: str | None = None) Tuple[int, str, str][源代码]

获取错误页面

参数:
  • status_code -- HTTP 状态码

  • message -- 自定义错误消息

  • detail -- 自定义错误详情

返回:

(状态码, 内容类型, HTML 内容)

render_error_page(status_code: int, message: str | None = None, detail: str | None = None) str[源代码]

渲染错误页面

参数:
  • status_code -- HTTP 状态码

  • message -- 自定义错误消息

  • detail -- 自定义错误详情

返回:

HTML 错误页面

class litefs.FileEventHandler(app)[源代码]

基类:FileSystemEventHandler

add_monitored_file(path)[源代码]

添加需要监控的文件

参数:

path -- 文件路径

on_created(event)[源代码]

Called when a file or directory is created.

参数:

event (DirCreatedEvent or FileCreatedEvent) -- Event representing file/directory creation.

on_deleted(event)[源代码]

Called when a file or directory is deleted.

参数:

event (DirDeletedEvent or FileDeletedEvent) -- Event representing file/directory deletion.

on_modified(event)[源代码]

Called when a file or directory is modified.

参数:

event (DirModifiedEvent or FileModifiedEvent) -- Event representing file/directory modification.

on_moved(event)[源代码]

Called when a file or a directory is moved or renamed.

参数:

event (DirMovedEvent or FileMovedEvent) -- Event representing file/directory movement.

class litefs.FormValidator[源代码]

基类:object

表单验证器

add_field(field_name: str, validators: Validator | List[Validator])[源代码]

添加字段验证器

参数:
  • field_name -- 字段名称

  • validators -- 验证器或验证器列表

get_errors() List[ValidationError][源代码]

获取所有验证错误

validate(data: Dict[str, Any]) Tuple[bool, Dict[str, List[str]]][源代码]

验证表单数据

参数:

data -- 表单数据字典

返回:

(是否验证成功, 错误字典)

class litefs.HTTPServer(server_address, RequestHandlerClass, bind_and_activate=True)[源代码]

基类:TCPServer

allow_reuse_address = 1
max_request_size = 10485760
server_bind()[源代码]
exception litefs.HttpError(status_code=500, message='Internal Server Error')[源代码]

基类:Exception

class litefs.LiteFile(path, base, name, text, status_code=200)[源代码]

基类:object

handler(request)[源代码]
class litefs.Litefs(**kwargs: Dict[str, Any])[源代码]

基类:object

add_delete(path, handler=None, name=None)[源代码]

添加 DELETE 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_get(path, handler=None, name=None)[源代码]

添加 GET 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_head(path, handler=None, name=None)[源代码]

添加 HEAD 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_health_check(name: str, check_func)[源代码]

添加健康检查

参数:
  • name -- 检查名称

  • check_func -- 检查函数,返回 True 表示健康,False 表示不健康

add_middleware(middleware_class, **kwargs)[源代码]

添加中间件

参数:
  • middleware_class -- 中间件类

  • **kwargs -- 传递给中间件构造函数的参数

返回:

支持链式调用

返回类型:

self

add_options(path, handler=None, name=None)[源代码]

添加 OPTIONS 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_patch(path, handler=None, name=None)[源代码]

添加 PATCH 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_post(path, handler=None, name=None)[源代码]

添加 POST 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_put(path, handler=None, name=None)[源代码]

添加 PUT 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_ready_check(name: str, check_func)[源代码]

添加就绪检查

参数:
  • name -- 检查名称

  • check_func -- 检查函数,返回 True 表示就绪,False 表示未就绪

add_route(path, methods=None, handler=None, name=None)[源代码]

添加路由

参数:
  • path -- 路由路径

  • methods -- HTTP 方法列表,默认 ['GET']

  • handler -- 处理函数

  • name -- 路由名称

add_static(prefix: str, directory: str, name: str | None = None)[源代码]

添加静态文件路由

参数:
  • prefix -- URL 前缀,如 '/static'

  • directory -- 静态文件目录路径

  • name -- 路由名称

clear_middleware()[源代码]

清空所有中间件

create_all_tables(name: str = 'default')[源代码]

创建所有数据表

参数:

name -- 数据库名称

database(name: str = 'default') Any[源代码]

获取数据库实例

参数:

name -- 数据库名称

返回:

数据库实例

db_session(name: str = 'default') Any[源代码]

获取数据库会话

参数:

name -- 数据库名称

返回:

数据库会话实例

drop_all_tables(name: str = 'default')[源代码]

删除所有数据表

参数:

name -- 数据库名称

get_all_plugins()[源代码]

获取所有已加载的插件

返回:

插件实例列表

get_plugin(plugin_name: str)[源代码]

获取插件实例

参数:

plugin_name -- 插件名称

返回:

插件实例或 None

handler(request, rw, environ, server)[源代码]
has_plugin(plugin_name: str) bool[源代码]

检查插件是否已加载

参数:

plugin_name -- 插件名称

返回:

是否已加载

load_plugins()[源代码]

加载所有插件

register_plugin(plugin_class)[源代码]

注册插件

参数:

plugin_class -- 插件类

register_routes(module)[源代码]

注册模块中的路由

参数:

module -- 包含路由装饰器的模块对象或模块名称

remove_middleware(middleware_class)[源代码]

移除中间件

参数:

middleware_class -- 中间件类

run(poll_interval=0.2, processes=1, no_reload=False)[源代码]
session(name: str = 'default') Any[源代码]

获取数据库会话(别名,已废弃,建议使用 db_session)

参数:

name -- 数据库名称

返回:

数据库会话实例

url_for(name, **kwargs)[源代码]

根据路由名称生成 URL

参数:
  • name -- 路由名称

  • **kwargs -- 路由参数

返回:

生成的 URL

wsgi()[源代码]

返回符合 PEP 3333 规范的 WSGI application callable

用法:

import litefs app = litefs.Litefs() application = app.wsgi()

在 gunicorn 中使用:

gunicorn -w 4 -b :8000 wsgi_example:application

在 uWSGI 中使用:

uwsgi --http :8000 --wsgi-file wsgi_example.py

class litefs.MemoryCache(max_size=10000)[源代码]

基类:object

delete(key)[源代码]
get(key)[源代码]
put(key, val)[源代码]
class litefs.NumberValidator(min_value: int | float | None = None, max_value: int | float | None = None, message: str | None = None)[源代码]

基类:Validator

数字验证器

validate(value: Any, field_name: str | None = None) Any[源代码]

验证值

参数:
  • value -- 要验证的值

  • field_name -- 字段名称

返回:

验证后的值

抛出:

ValidationError -- 验证失败

class litefs.RedisCache(redis_client=None, host: str = 'localhost', port: int = 6379, db: int = 0, password: str | None = None, key_prefix: str = 'litefs:', expiration_time: int = 3600, **kwargs)[源代码]

基类:object

Redis 缓存实现

使用 Redis 作为缓存后端,提供高性能的分布式缓存支持

clear() None[源代码]

清空所有缓存

注意:这会删除所有带前缀的键

close() None[源代码]

关闭 Redis 连接

delete(key: str) None[源代码]

从缓存删除值

参数:

key -- 缓存键

delete_many(keys: list) None[源代码]

批量删除键

参数:

keys -- 缓存键列表

delete_pattern(pattern: str) int[源代码]

删除匹配模式的键

参数:

pattern -- 键模式

返回:

删除的键数量

exists(key: str) bool[源代码]

检查键是否存在

参数:

key -- 缓存键

返回:

键是否存在

expire(key: str, expiration: int) bool[源代码]

设置键的过期时间

参数:
  • key -- 缓存键

  • expiration -- 过期时间(秒)

返回:

是否设置成功

get(key: str) Any | None[源代码]

从缓存获取值

参数:

key -- 缓存键

返回:

缓存值,如果不存在则返回 None

get_many(keys: list) dict[源代码]

批量获取值

参数:

keys -- 缓存键列表

返回:

键值字典

put(key: str, val: Any, expiration: int | None = None) None[源代码]

存储值到缓存

参数:
  • key -- 缓存键

  • val -- 缓存值

  • expiration -- 过期时间(秒),如果为 None 则使用默认过期时间

set_many(mapping: dict, expiration: int | None = None) None[源代码]

批量存储值

参数:
  • mapping -- 键值字典

  • expiration -- 过期时间(秒),如果为 None 则使用默认过期时间

ttl(key: str) int[源代码]

获取键的剩余过期时间

参数:

key -- 缓存键

返回:

剩余过期时间(秒),如果键不存在则返回 -2

class litefs.RegexValidator(pattern: str, message: str = '格式不正确')[源代码]

基类:Validator

正则表达式验证器

validate(value: Any, field_name: str | None = None) Any[源代码]

验证值

参数:
  • value -- 要验证的值

  • field_name -- 字段名称

返回:

验证后的值

抛出:

ValidationError -- 验证失败

class litefs.RequestHandler(app, rw, environ, request)[源代码]

基类:BaseRequestHandler

property body
property charset
property config
property content_length
property content_type
property cookie
property data
default_headers = {'Content-Type': 'application/json; charset=utf-8', 'Server': 'litefs/0.4.0', 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'SAMEORIGIN', 'X-XSS-Protection': '1; mode=block'}
property environ
property files
finish(content)[源代码]
handle_response(result)[源代码]

处理响应结果,支持 Response 对象

handler()[源代码]
property json
property method
property params
property path_info
property query_string
redirect(url=None)[源代码]
property referer
property request_method
property request_uri
property server_protocol
property session
property session_id
class litefs.RequiredValidator(message: str = '此字段为必填项')[源代码]

基类:Validator

必填验证器

validate(value: Any, field_name: str | None = None) Any[源代码]

验证值

参数:
  • value -- 要验证的值

  • field_name -- 字段名称

返回:

验证后的值

抛出:

ValidationError -- 验证失败

class litefs.Response(content=None, status_code=200, headers=None)[源代码]

基类:object

响应对象,提供更丰富的响应方法

classmethod error(status_code, message=None, headers=None)[源代码]

返回错误响应

classmethod file(file_path, status_code=200, headers=None)[源代码]

返回文件响应

classmethod html(content, status_code=200, headers=None)[源代码]

返回 HTML 响应

classmethod json(data, status_code=200, headers=None)[源代码]

返回 JSON 响应

classmethod redirect(url, status_code=302, headers=None)[源代码]

返回重定向响应

classmethod text(content, status_code=200, headers=None)[源代码]

返回纯文本响应

class litefs.Session(session_id=None, store=None)[源代码]

基类:UserDict

Session 数据对象

继承自 UserDict,用于存储单个 Session 的数据

save()[源代码]

手动保存 Session 数据到存储后端

class litefs.StringValidator(min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, message: str | None = None)[源代码]

基类:Validator

字符串验证器

validate(value: Any, field_name: str | None = None) Any[源代码]

验证值

参数:
  • value -- 要验证的值

  • field_name -- 字段名称

返回:

验证后的值

抛出:

ValidationError -- 验证失败

class litefs.TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)[源代码]

基类:object

Classic Python TCPServer

address_family = 2
allow_reuse_address = True
close_request(request)[源代码]
fileno()[源代码]
finish_request(request, client_address)[源代码]
get_request()[源代码]
handle_error(request, client_address)[源代码]
handle_request()[源代码]
handle_timeout()[源代码]
process_request(request, client_address)[源代码]
request_queue_size = 4194304
server_activate()[源代码]
server_bind()[源代码]
server_close()[源代码]
server_forever(poll_interval=0.1)[源代码]
shutdown()[源代码]
shutdown_request(request)[源代码]
socket_type = 1
start()[源代码]
verify_request(request, client_address)[源代码]
class litefs.TreeCache(clean_period=60, expiration_time=3600)[源代码]

基类:object

auto_clean()[源代码]

优化的清理机制

避免每次清理都查询数据库,只在清理周期到达时执行清理

delete(key)[源代码]
get(key)[源代码]
put(key, val)[源代码]
class litefs.TypeValidator(expected_type: type, message: str | None = None)[源代码]

基类:Validator

类型验证器

validate(value: Any, field_name: str | None = None) Any[源代码]

验证值

参数:
  • value -- 要验证的值

  • field_name -- 字段名称

返回:

验证后的值

抛出:

ValidationError -- 验证失败

class litefs.URLValidator(message: str = '请输入有效的 URL')[源代码]

基类:Validator

URL 验证器

validate(value: Any, field_name: str | None = None) Any[源代码]

验证值

参数:
  • value -- 要验证的值

  • field_name -- 字段名称

返回:

验证后的值

抛出:

ValidationError -- 验证失败

exception litefs.ValidationError(message: str, field: str | None = None)[源代码]

基类:Exception

验证错误异常

class litefs.Validator(message: str | None = None)[源代码]

基类:object

验证器基类

validate(value: Any, field_name: str | None = None) Any[源代码]

验证值

参数:
  • value -- 要验证的值

  • field_name -- 字段名称

返回:

验证后的值

抛出:

ValidationError -- 验证失败

class litefs.WSGIRequestHandler(app, environ)[源代码]

基类:BaseRequestHandler

WSGI 请求处理器,用于在 gunicorn、uWSGI 等 WSGI 服务器中运行

符合 PEP 3333 规范,处理 WSGI environ 并返回标准响应

property body
property charset
property config
property content_length
property content_type
property cookie
property data
property environ
property files
handler()[源代码]
property json
property method
property params
property path_info
property query_string
property referer
property request_method
property request_uri
property server_protocol
property session
property session_id
class litefs.WSGIServer(server_address, RequestHandlerClass, bind_and_activate=True)[源代码]

基类:HTTPServer

application = None
get_app()[源代码]
server_bind()[源代码]
set_app(application)[源代码]
setup_environ()[源代码]
litefs.choice(choices: List[Any], message: str | None = None) ChoiceValidator[源代码]

选择验证器快捷函数

litefs.cli_main()

主函数

litefs.email(message: str = '请输入有效的邮箱地址') EmailValidator[源代码]

邮箱验证器快捷函数

litefs.get_global_cache(backend: str = 'tree', **kwargs) MemoryCache | TreeCache | RedisCache | DatabaseCache | MemcacheCache[源代码]

获取全局缓存实例的便捷函数

参数:
  • backend -- 缓存后端类型

  • **kwargs -- 缓存配置参数

返回:

缓存实例

litefs.gmt_date(timestamp=None)[源代码]
litefs.load_config(config_file: str | None = None, env_prefix: str | None = None, **kwargs) Config[源代码]

加载配置

参数:
  • config_file -- 配置文件路径

  • env_prefix -- 环境变量前缀(默认为 LITEFS_

  • **kwargs -- 其他配置项

返回:

Config 对象

litefs.log_debug(logger, message=None)[源代码]
litefs.log_error(logger, message=None)[源代码]
litefs.log_info(logger, message=None)[源代码]
litefs.mainloop(poll_interval=0.1)[源代码]
litefs.make_config(**kwargs: Dict[str, Any]) Config[源代码]

创建配置对象

支持多种配置来源: 1. 默认配置 2. 配置文件(通过 config_file 参数) 3. 环境变量(LITEFS_*) 4. 代码中的配置(kwargs)

参数:

**kwargs -- 配置项

返回:

Config 对象

litefs.make_environ(server, rw, client_address)[源代码]
litefs.make_headers(rw)[源代码]
litefs.make_logger(name, log=None, level=20)[源代码]
litefs.make_server(host: str, port: int, request_size: int = -1) socket[源代码]
litefs.merge_configs(*configs: Config | Dict[str, Any]) Config[源代码]

合并多个配置

参数:

*configs -- 配置对象或字典

返回:

合并后的 Config 对象

litefs.number_type(min_value: int | float | None = None, max_value: int | float | None = None, message: str | None = None) NumberValidator[源代码]

数字验证器快捷函数

litefs.parse_form(query_string)[源代码]

解析表单数据,支持缓存

参数:

query_string -- 查询字符串

返回:

解析后的表单数据字典

litefs.regex(pattern: str, message: str = '格式不正确') RegexValidator[源代码]

正则表达式验证器快捷函数

litefs.render_error()[源代码]
litefs.required(message: str = '此字段为必填项') RequiredValidator[源代码]

必填验证器快捷函数

litefs.string_type(min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, message: str | None = None) StringValidator[源代码]

字符串验证器快捷函数

litefs.test_server()[源代码]
litefs.url(message: str = '请输入有效的 URL') URLValidator[源代码]

URL 验证器快捷函数

Subpackages

Submodules

litefs.config module

class litefs.config.Config(config_file: str | None = None, **kwargs)[源代码]

基类:object

配置管理类

支持多种配置来源和分层管理: 1. 默认配置(内置) 2. 环境配置(如 config.production.yaml) 3. 本地配置(如 config.local.yaml) 4. 环境变量 5. 代码中的配置

配置优先级(从高到低): 代码配置 > 环境变量 > 本地配置 > 环境配置 > 默认值

DEFAULT_CONFIG = {'cache_backend': 'tree', 'cache_clean_period': 60, 'cache_expiration_time': 3600, 'cache_max_size': 10000, 'config_encrypted_keys': [], 'config_env': None, 'config_file': None, 'config_secret_key': None, 'database_cache_table': 'cache', 'database_session_table': 'sessions', 'database_url': None, 'debug': False, 'default_page': 'index,index.html', 'error_pages_dir': None, 'file_cache_clean_period': 60, 'file_cache_expiration_time': 3600, 'host': 'localhost', 'listen': 1024, 'log': './default.log', 'max_request_size': 10485760, 'max_upload_size': 52428800, 'memcache_key_prefix': 'litefs:', 'memcache_servers': 'localhost:11211', 'memcache_session_key_prefix': 'litefs:session:', 'port': 9090, 'redis_db': 0, 'redis_host': 'localhost', 'redis_key_prefix': 'litefs:', 'redis_password': None, 'redis_port': 6379, 'redis_session_key_prefix': 'litefs:session:', 'session_backend': 'memory', 'session_expiration_time': 3600, 'session_http_only': True, 'session_max_size': 1000000, 'session_name': 'litefs.sid', 'session_same_site': 'Lax', 'session_secure': False}
ENV_PREFIX = 'LITEFS_'
decrypt_config(encrypted_value: str) Any[源代码]

解密配置值

参数:

encrypted_value -- 加密后的字符串

返回:

解密后的值

encrypt_config(key: str, value: Any) str[源代码]

加密配置值

参数:
  • key -- 配置键

  • value -- 配置值

返回:

加密后的字符串

get(key: str, default: Any | None = None) Any[源代码]

获取配置项

参数:
  • key -- 配置键

  • default -- 默认值

返回:

配置值

items() List[tuple][源代码]

获取所有配置项

keys() List[str][源代码]

获取所有配置键

set(key: str, value: Any)[源代码]

设置配置项

参数:
  • key -- 配置键

  • value -- 配置值

to_dict() Dict[str, Any][源代码]

转换为字典

返回:

配置字典

update(**kwargs)[源代码]

批量更新配置

参数:

**kwargs -- 配置项

values() List[Any][源代码]

获取所有配置值

litefs.config.load_config(config_file: str | None = None, env_prefix: str | None = None, **kwargs) Config[源代码]

加载配置

参数:
  • config_file -- 配置文件路径

  • env_prefix -- 环境变量前缀(默认为 LITEFS_

  • **kwargs -- 其他配置项

返回:

Config 对象

litefs.config.merge_configs(*configs: Config | Dict[str, Any]) Config[源代码]

合并多个配置

参数:

*configs -- 配置对象或字典

返回:

合并后的 Config 对象

litefs.core module

class litefs.core.Litefs(**kwargs: Dict[str, Any])[源代码]

基类:object

add_delete(path, handler=None, name=None)[源代码]

添加 DELETE 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_get(path, handler=None, name=None)[源代码]

添加 GET 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_head(path, handler=None, name=None)[源代码]

添加 HEAD 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_health_check(name: str, check_func)[源代码]

添加健康检查

参数:
  • name -- 检查名称

  • check_func -- 检查函数,返回 True 表示健康,False 表示不健康

add_middleware(middleware_class, **kwargs)[源代码]

添加中间件

参数:
  • middleware_class -- 中间件类

  • **kwargs -- 传递给中间件构造函数的参数

返回:

支持链式调用

返回类型:

self

add_options(path, handler=None, name=None)[源代码]

添加 OPTIONS 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_patch(path, handler=None, name=None)[源代码]

添加 PATCH 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_post(path, handler=None, name=None)[源代码]

添加 POST 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_put(path, handler=None, name=None)[源代码]

添加 PUT 方法路由

参数:
  • path -- 路由路径

  • handler -- 处理函数

  • name -- 路由名称

add_ready_check(name: str, check_func)[源代码]

添加就绪检查

参数:
  • name -- 检查名称

  • check_func -- 检查函数,返回 True 表示就绪,False 表示未就绪

add_route(path, methods=None, handler=None, name=None)[源代码]

添加路由

参数:
  • path -- 路由路径

  • methods -- HTTP 方法列表,默认 ['GET']

  • handler -- 处理函数

  • name -- 路由名称

add_static(prefix: str, directory: str, name: str | None = None)[源代码]

添加静态文件路由

参数:
  • prefix -- URL 前缀,如 '/static'

  • directory -- 静态文件目录路径

  • name -- 路由名称

clear_middleware()[源代码]

清空所有中间件

create_all_tables(name: str = 'default')[源代码]

创建所有数据表

参数:

name -- 数据库名称

database(name: str = 'default') Any[源代码]

获取数据库实例

参数:

name -- 数据库名称

返回:

数据库实例

db_session(name: str = 'default') Any[源代码]

获取数据库会话

参数:

name -- 数据库名称

返回:

数据库会话实例

drop_all_tables(name: str = 'default')[源代码]

删除所有数据表

参数:

name -- 数据库名称

get_all_plugins()[源代码]

获取所有已加载的插件

返回:

插件实例列表

get_plugin(plugin_name: str)[源代码]

获取插件实例

参数:

plugin_name -- 插件名称

返回:

插件实例或 None

handler(request, rw, environ, server)[源代码]
has_plugin(plugin_name: str) bool[源代码]

检查插件是否已加载

参数:

plugin_name -- 插件名称

返回:

是否已加载

load_plugins()[源代码]

加载所有插件

register_plugin(plugin_class)[源代码]

注册插件

参数:

plugin_class -- 插件类

register_routes(module)[源代码]

注册模块中的路由

参数:

module -- 包含路由装饰器的模块对象或模块名称

remove_middleware(middleware_class)[源代码]

移除中间件

参数:

middleware_class -- 中间件类

run(poll_interval=0.2, processes=1, no_reload=False)[源代码]
session(name: str = 'default') Any[源代码]

获取数据库会话(别名,已废弃,建议使用 db_session)

参数:

name -- 数据库名称

返回:

数据库会话实例

url_for(name, **kwargs)[源代码]

根据路由名称生成 URL

参数:
  • name -- 路由名称

  • **kwargs -- 路由参数

返回:

生成的 URL

wsgi()[源代码]

返回符合 PEP 3333 规范的 WSGI application callable

用法:

import litefs app = litefs.Litefs() application = app.wsgi()

在 gunicorn 中使用:

gunicorn -w 4 -b :8000 wsgi_example:application

在 uWSGI 中使用:

uwsgi --http :8000 --wsgi-file wsgi_example.py

litefs.core.is_port_available(host: str, port: int) bool[源代码]

检查端口是否可用

参数:
  • host -- 主机地址

  • port -- 端口号

返回:

端口是否可用

返回类型:

bool

litefs.core.make_config(**kwargs: Dict[str, Any]) Config[源代码]

创建配置对象

支持多种配置来源: 1. 默认配置 2. 配置文件(通过 config_file 参数) 3. 环境变量(LITEFS_*) 4. 代码中的配置(kwargs)

参数:

**kwargs -- 配置项

返回:

Config 对象

litefs.core.make_server(host: str, port: int, request_size: int = -1) socket[源代码]
litefs.core.test_server()[源代码]

litefs.exceptions module

exception litefs.exceptions.HttpError(status_code=500, message='Internal Server Error')[源代码]

基类:Exception

exception litefs.exceptions.RouteNotFound[源代码]

基类:Exception

路由未找到异常