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 实例
- 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_'
- 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
- set_cookie(key: str, value: str, **kwargs)[源代码]
设置 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 -- 验证规则字典 {字段名: [验证器列表]}
- 返回:
(是否验证成功, 错误字典)
- 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 '}
- class litefs.FileEventHandler(app)[源代码]
基类:
FileSystemEventHandler- on_created(event)[源代码]
Called when a file or directory is created.
- 参数:
event (
DirCreatedEventorFileCreatedEvent) -- Event representing file/directory creation.
- on_deleted(event)[源代码]
Called when a file or directory is deleted.
- 参数:
event (
DirDeletedEventorFileDeletedEvent) -- Event representing file/directory deletion.
- class litefs.FormValidator[源代码]
基类:
object表单验证器
- add_field(field_name: str, validators: Validator | List[Validator])[源代码]
添加字段验证器
- 参数:
field_name -- 字段名称
validators -- 验证器或验证器列表
- get_errors() List[ValidationError][源代码]
获取所有验证错误
- class litefs.HTTPServer(server_address, RequestHandlerClass, bind_and_activate=True)[源代码]
基类:
TCPServer- allow_reuse_address = 1
- max_request_size = 10485760
- 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 -- 路由名称
- 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)[源代码]
基类:
objectRedis 缓存实现
使用 Redis 作为缓存后端,提供高性能的分布式缓存支持
- expire(key: str, expiration: int) bool[源代码]
设置键的过期时间
- 参数:
key -- 缓存键
expiration -- 过期时间(秒)
- 返回:
是否设置成功
- put(key: str, val: Any, expiration: int | None = None) None[源代码]
存储值到缓存
- 参数:
key -- 缓存键
val -- 缓存值
expiration -- 过期时间(秒),如果为 None 则使用默认过期时间
- 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)[源代码]
-
- 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
- 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.RequiredValidator(message: str = '此字段为必填项')[源代码]
基类:
Validator必填验证器
- validate(value: Any, field_name: str | None = None) Any[源代码]
验证值
- 参数:
value -- 要验证的值
field_name -- 字段名称
- 返回:
验证后的值
- 抛出:
ValidationError -- 验证失败
- class litefs.Session(session_id=None, store=None)[源代码]
基类:
UserDictSession 数据对象
继承自 UserDict,用于存储单个 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)[源代码]
基类:
objectClassic Python TCPServer
- address_family = 2
- allow_reuse_address = True
- request_queue_size = 4194304
- socket_type = 1
- 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')[源代码]
基类:
ValidatorURL 验证器
- validate(value: Any, field_name: str | None = None) Any[源代码]
验证值
- 参数:
value -- 要验证的值
field_name -- 字段名称
- 返回:
验证后的值
- 抛出:
ValidationError -- 验证失败
- 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)[源代码]
-
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
- 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
- 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.load_config(config_file: str | None = None, env_prefix: str | None = None, **kwargs) Config[源代码]
加载配置
- 参数:
config_file -- 配置文件路径
env_prefix -- 环境变量前缀(默认为 LITEFS_)
**kwargs -- 其他配置项
- 返回:
Config 对象
- litefs.make_config(**kwargs: Dict[str, Any]) Config[源代码]
创建配置对象
支持多种配置来源: 1. 默认配置 2. 配置文件(通过 config_file 参数) 3. 环境变量(LITEFS_*) 4. 代码中的配置(kwargs)
- 参数:
**kwargs -- 配置项
- 返回:
Config 对象
- 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.regex(pattern: str, message: str = '格式不正确') RegexValidator[源代码]
正则表达式验证器快捷函数
- 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.url(message: str = '请输入有效的 URL') URLValidator[源代码]
URL 验证器快捷函数
Subpackages
- litefs.cache package
- litefs.handlers package
EnhancedRequestHandlerEnhancedRequestHandler.bodyEnhancedRequestHandler.configEnhancedRequestHandler.content_lengthEnhancedRequestHandler.content_typeEnhancedRequestHandler.cookieEnhancedRequestHandler.environEnhancedRequestHandler.filesEnhancedRequestHandler.get_file()EnhancedRequestHandler.get_post_param()EnhancedRequestHandler.get_query_param()EnhancedRequestHandler.jsonEnhancedRequestHandler.path_infoEnhancedRequestHandler.postEnhancedRequestHandler.queryEnhancedRequestHandler.query_stringEnhancedRequestHandler.refererEnhancedRequestHandler.request_methodEnhancedRequestHandler.request_uriEnhancedRequestHandler.sessionEnhancedRequestHandler.session_idEnhancedRequestHandler.set_cookie()EnhancedRequestHandler.set_form_validator()EnhancedRequestHandler.start_response()EnhancedRequestHandler.validate_all()EnhancedRequestHandler.validate_files()EnhancedRequestHandler.validate_post()EnhancedRequestHandler.validate_query()
RequestHandlerRequestHandler.bodyRequestHandler.charsetRequestHandler.configRequestHandler.content_lengthRequestHandler.content_typeRequestHandler.cookieRequestHandler.dataRequestHandler.default_headersRequestHandler.environRequestHandler.filesRequestHandler.finish()RequestHandler.handle_response()RequestHandler.handler()RequestHandler.jsonRequestHandler.methodRequestHandler.paramsRequestHandler.path_infoRequestHandler.query_stringRequestHandler.redirect()RequestHandler.refererRequestHandler.request_methodRequestHandler.request_uriRequestHandler.server_protocolRequestHandler.sessionRequestHandler.session_idRequestHandler.set_cookie()
ResponseWSGIRequestHandlerWSGIRequestHandler.bodyWSGIRequestHandler.charsetWSGIRequestHandler.configWSGIRequestHandler.content_lengthWSGIRequestHandler.content_typeWSGIRequestHandler.cookieWSGIRequestHandler.dataWSGIRequestHandler.environWSGIRequestHandler.filesWSGIRequestHandler.handler()WSGIRequestHandler.jsonWSGIRequestHandler.methodWSGIRequestHandler.paramsWSGIRequestHandler.path_infoWSGIRequestHandler.query_stringWSGIRequestHandler.refererWSGIRequestHandler.request_methodWSGIRequestHandler.request_uriWSGIRequestHandler.server_protocolWSGIRequestHandler.sessionWSGIRequestHandler.session_idWSGIRequestHandler.set_cookie()
- Submodules
- litefs.handlers.request module
BaseRequestHandlerBaseRequestHandler.appBaseRequestHandler.bodyBaseRequestHandler.filesBaseRequestHandler.formBaseRequestHandler.getBaseRequestHandler.postBaseRequestHandler.render_template()BaseRequestHandler.sessionBaseRequestHandler.session_idBaseRequestHandler.set_cookie()BaseRequestHandler.start_response()
RequestHandlerRequestHandler.bodyRequestHandler.charsetRequestHandler.configRequestHandler.content_lengthRequestHandler.content_typeRequestHandler.cookieRequestHandler.dataRequestHandler.default_headersRequestHandler.environRequestHandler.filesRequestHandler.finish()RequestHandler.handle_response()RequestHandler.handler()RequestHandler.jsonRequestHandler.methodRequestHandler.paramsRequestHandler.path_infoRequestHandler.query_stringRequestHandler.redirect()RequestHandler.refererRequestHandler.request_methodRequestHandler.request_uriRequestHandler.server_protocolRequestHandler.sessionRequestHandler.session_idRequestHandler.set_cookie()
ResponseWSGIRequestHandlerWSGIRequestHandler.bodyWSGIRequestHandler.charsetWSGIRequestHandler.configWSGIRequestHandler.content_lengthWSGIRequestHandler.content_typeWSGIRequestHandler.cookieWSGIRequestHandler.dataWSGIRequestHandler.environWSGIRequestHandler.filesWSGIRequestHandler.handler()WSGIRequestHandler.jsonWSGIRequestHandler.methodWSGIRequestHandler.paramsWSGIRequestHandler.path_infoWSGIRequestHandler.query_stringWSGIRequestHandler.refererWSGIRequestHandler.request_methodWSGIRequestHandler.request_uriWSGIRequestHandler.server_protocolWSGIRequestHandler.sessionWSGIRequestHandler.session_idWSGIRequestHandler.set_cookie()
double_slash_sub()form_dict_match()imap()is_bytes()parse_form()parse_header()startswith_dot_sub()
- litefs.middleware package
AuthMiddlewareCORSMiddlewareCSRFMiddlewareHealthCheckLoggingMiddlewareMiddlewareMiddlewareManagerRateLimitMiddlewareSecurityMiddlewareThrottleMiddleware- Submodules
- litefs.middleware.base module
- litefs.middleware.cors module
- litefs.middleware.health_check module
- litefs.middleware.logging module
- litefs.middleware.rate_limit module
- litefs.middleware.security module
- litefs.server package
BufferedRWPairHTTPServerProcessHTTPServerSocketIOTCPServerTCPServer.address_familyTCPServer.allow_reuse_addressTCPServer.close_request()TCPServer.fileno()TCPServer.finish_request()TCPServer.get_request()TCPServer.handle_error()TCPServer.handle_request()TCPServer.handle_timeout()TCPServer.process_request()TCPServer.request_queue_sizeTCPServer.server_activate()TCPServer.server_bind()TCPServer.server_close()TCPServer.server_forever()TCPServer.shutdown()TCPServer.shutdown_request()TCPServer.socket_typeTCPServer.start()TCPServer.verify_request()
WSGIServermainloop()make_environ()make_headers()- Submodules
- litefs.server.http_server module
EpollHTTPServerProcessHTTPServerSocketIOTCPServerTCPServer.address_familyTCPServer.allow_reuse_addressTCPServer.close_request()TCPServer.fileno()TCPServer.finish_request()TCPServer.get_request()TCPServer.handle_error()TCPServer.handle_request()TCPServer.handle_timeout()TCPServer.process_request()TCPServer.request_queue_sizeTCPServer.server_activate()TCPServer.server_bind()TCPServer.server_close()TCPServer.server_forever()TCPServer.shutdown()TCPServer.shutdown_request()TCPServer.socket_typeTCPServer.start()TCPServer.verify_request()
WSGIServermainloop()make_environ()make_headers()parse_header()server_forever()
- litefs.session package
- litefs.utils package
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_'
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 -- 路由名称
- litefs.core.is_port_available(host: str, port: int) bool[源代码]
检查端口是否可用
- 参数:
host -- 主机地址
port -- 端口号
- 返回:
端口是否可用
- 返回类型:
bool