API 文档
Generated by TRAE SOLO at 2026-03-27
概述
Litefs 提供了完整的 Python API,支持快速构建 Web 应用程序。
核心类
Litefs
Litefs 是核心应用类,用于创建和管理 Web 服务器。
构造函数
Litefs(**kwargs)
参数:
参数 |
类型 |
默认值 |
说明 |
|---|---|---|---|
|
str |
|
服务器监听地址 |
|
int |
|
服务器监听端口 |
|
bool |
|
调试模式 |
|
str |
|
404 页面文件名 |
|
str |
|
默认页面文件名(支持多个,逗号分隔) |
|
str |
|
日志文件路径 |
|
int |
|
服务器监听队列大小 |
|
int |
|
最大请求体大小(字节) |
|
int |
|
最大上传文件大小(字节) |
|
str |
|
配置文件路径 |
示例:
from litefs import Litefs
app = Litefs(
host='0.0.0.0',
port=8080,
debug=True,
)
方法
run()
启动服务器。
app.run()
wsgi()
返回符合 PEP 3333 规范的 WSGI application callable。
application = app.wsgi()
示例:
from litefs import Litefs
app = Litefs()
application = app.wsgi()
# 在 Gunicorn 中使用
# gunicorn -w 4 -b :8000 wsgi_example:application
add_middleware()
添加中间件。
app.add_middleware(MiddlewareClass, **middleware_kwargs)
参数:
MiddlewareClass: 中间件类**middleware_kwargs: 中间件参数
返回:
self- 支持链式调用
示例:
from litefs import Litefs
from litefs.middleware import LoggingMiddleware, SecurityMiddleware
app = Litefs()
app.add_middleware(LoggingMiddleware)
app.add_middleware(SecurityMiddleware)
# 链式调用
app = (
Litefs()
.add_middleware(LoggingMiddleware)
.add_middleware(SecurityMiddleware)
)
remove_middleware()
移除中间件。
app.remove_middleware(MiddlewareClass)
参数:
MiddlewareClass: 要移除的中间件类
clear_middleware()
清空所有中间件。
app.clear_middleware()
add_health_check()
添加健康检查。
app.add_health_check(name, check_func)
参数:
name: 检查名称check_func: 检查函数,返回 bool
示例:
def check_database():
try:
db.connect()
return True
except Exception:
return False
app.add_health_check('database', check_database)
add_ready_check()
添加就绪检查。
app.add_ready_check(name, check_func)
参数:
name: 检查名称check_func: 检查函数,返回 bool
示例:
def check_migrations():
return migration_status.is_complete()
app.add_ready_check('migrations', check_migrations)
add_get()
添加 GET 路由。
app.add_get(path, handler=None, name=None)
参数:
path: 路由路径(支持路径参数,如/user/{id})handler: 处理函数(可选,支持装饰器风格)name: 路由名称(可选)
返回:
装饰器函数(当 handler 为 None 时)或 self
示例:
# 方法链风格
def index_handler(request):
return 'Hello, World!'
app.add_get('/', index_handler, name='index')
# 装饰器风格
@app.add_get('/hello', name='hello')
def hello_handler(request):
return 'Hello, World!'
add_post()
添加 POST 路由。
app.add_post(path, handler=None, name=None)
参数:
path: 路由路径handler: 处理函数(可选)name: 路由名称(可选)
返回:
装饰器函数或 self
示例:
@app.add_post('/login', name='login')
def login_handler(request):
username = request.data.get('username')
password = request.data.get('password')
return {'status': 'success'}
add_put()
添加 PUT 路由。
app.add_put(path, handler=None, name=None)
参数:
path: 路由路径handler: 处理函数(可选)name: 路由名称(可选)
返回:
装饰器函数或 self
add_delete()
添加 DELETE 路由。
app.add_delete(path, handler=None, name=None)
参数:
path: 路由路径handler: 处理函数(可选)name: 路由名称(可选)
返回:
装饰器函数或 self
add_patch()
添加 PATCH 路由。
app.add_patch(path, handler=None, name=None)
参数:
path: 路由路径handler: 处理函数(可选)name: 路由名称(可选)
返回:
装饰器函数或 self
add_options()
添加 OPTIONS 路由。
app.add_options(path, handler=None, name=None)
参数:
path: 路由路径handler: 处理函数(可选)name: 路由名称(可选)
返回:
装饰器函数或 self
add_head()
添加 HEAD 路由。
app.add_head(path, handler=None, name=None)
参数:
path: 路由路径handler: 处理函数(可选)name: 路由名称(可选)
返回:
装饰器函数或 self
add_route()
添加通用路由。
app.add_route(method, path, handler=None, name=None)
参数:
method: HTTP 方法(GET, POST, PUT, DELETE 等)path: 路由路径handler: 处理函数(可选)name: 路由名称(可选)
返回:
装饰器函数或 self
示例:
app.add_route('GET', '/api/status', status_handler, name='api_status')
add_static()
添加静态文件路由。
app.add_static(prefix, directory, name=None)
参数:
prefix: URL 前缀(如/static)directory: 静态文件目录路径(如./static)name: 路由名称(可选)
示例:
app.add_static('/static', './static', name='static')
app.add_static('/uploads', './uploads', name='uploads')
register_routes()
注册装饰器定义的路由。
app.register_routes(module)
参数:
module: 模块对象或模块名称字符串
示例:
# 注册当前模块的路由
app.register_routes(__name__)
# 注册其他模块的路由
import routes_module
app.register_routes(routes_module)
# 注册模块名称字符串
app.register_routes('myapp.routes')
url_for()
根据路由名称生成 URL。
url = app.url_for(name, **params)
参数:
name: 路由名称**params: 路径参数
返回:
URL 字符串
示例:
url = app.url_for('user_detail', id=123) # 返回 '/user/123'
url = app.url_for('user_post', id=123, post_id=456) # 返回 '/user/123/posts/456'
属性
属性 |
类型 |
说明 |
|---|---|---|
|
Config |
配置对象 |
|
str |
服务器监听地址 |
|
int |
服务器监听端口 |
|
MemoryCache |
会话存储 |
|
TreeCache |
缓存存储 |
|
TreeCache |
文件缓存 |
|
MiddlewareManager |
中间件管理器 |
配置类
Config
配置管理类,支持多种配置来源。
构造函数
Config(config_file=None, **kwargs)
参数:
config_file: 配置文件路径(可选)**kwargs: 其他配置项
方法
get()
获取配置项。
value = config.get(key, default=None)
set()
设置配置项。
config.set(key, value)
update()
批量更新配置。
config.update(**kwargs)
to_dict()
转换为字典。
config_dict = config.to_dict()
keys()
获取所有配置键。
keys = config.keys()
values()
获取所有配置值。
values = config.values()
items()
获取所有配置项。
items = config.items()
属性访问
支持通过属性访问配置:
config = Config()
host = config.host
port = config.port
config.host = '0.0.0.0'
config.port = 8080
缓存类
MemoryCache
内存缓存实现,使用 LRU 策略。
构造函数
MemoryCache(max_size=10000)
参数:
max_size: 最大缓存条目数
方法
put()
添加缓存项。
cache.put(key, value)
get()
获取缓存项。
value = cache.get(key)
delete()
删除缓存项。
cache.delete(key)
clear()
清空缓存。
cache.clear()
size()
获取缓存大小。
size = cache.size()
TreeCache
树形缓存实现,支持层级结构。
构造函数
TreeCache(max_size=10000)
参数:
max_size: 最大缓存条目数
方法
put()
添加缓存项。
cache.put(key, value)
get()
获取缓存项。
value = cache.get(key)
delete()
删除缓存项。
cache.delete(key)
clear()
清空缓存。
cache.clear()
size()
获取缓存大小。
size = cache.size()
会话类
Session
会话管理类,用于存储用户会话数据。
构造函数
Session(session_id, cache)
参数:
session_id: 会话 IDcache: 缓存对象
方法
get()
获取会话数据。
value = session.get(key, default=None)
set()
设置会话数据。
session.set(key, value)
delete()
删除会话数据。
session.delete(key)
clear()
清空会话数据。
session.clear()
属性
属性 |
类型 |
说明 |
|---|---|---|
|
str |
会话 ID |
|
dict |
会话数据 |
中间件类
Middleware
中间件基类,所有中间件都应继承此类。
方法
process_request()
处理请求。
def process_request(self, request_handler):
pass
参数:
request_handler: 请求处理器
返回:
响应数据或 None
process_response()
处理响应。
def process_response(self, request_handler, response):
pass
参数:
request_handler: 请求处理器response: 响应数据
返回:
响应数据
示例
from litefs.middleware import Middleware
class CustomMiddleware(Middleware):
def process_request(self, request_handler):
print(f"请求: {request_handler.path_info}")
return None
def process_response(self, request_handler, response):
print(f"响应: {len(response)} bytes")
return response
LoggingMiddleware
日志中间件,记录请求和响应。
构造函数
LoggingMiddleware()
SecurityMiddleware
安全中间件,添加安全响应头。
构造函数
SecurityMiddleware()
CORSMiddleware
CORS 中间件,处理跨域请求。
构造函数
CORSMiddleware(
allow_origins=None,
allow_methods=None,
allow_headers=None,
allow_credentials=False,
max_age=86400,
)
参数:
allow_origins: 允许的来源列表allow_methods: 允许的方法列表allow_headers: 允许的头部列表allow_credentials: 是否允许凭证max_age: 预检请求缓存时间(秒)
RateLimitMiddleware
限流中间件,限制请求频率。
构造函数
RateLimitMiddleware(
max_requests=100,
window_seconds=60,
block_duration=120,
)
参数:
max_requests: 最大请求数window_seconds: 时间窗口(秒)block_duration: 封禁时长(秒)
HealthCheck
健康检查中间件。
构造函数
HealthCheck(path='/health', ready_path='/health/ready')
参数:
path: 健康检查端点路径ready_path: 就绪检查端点路径
工具函数
make_config()
创建配置对象。
config = make_config(**kwargs)
load_config()
加载配置。
config = load_config(config_file=None, env_prefix=None, **kwargs)
merge_configs()
合并多个配置。
merged = merge_configs(*configs)
parse_form()
解析表单数据。
form = parse_form(content_type, content)
参数:
content_type: Content-Type 头部content: 请求体内容
返回:
表单字典
make_logger()
创建日志记录器。
logger = make_logger(name, log=None, level=logging.INFO)
参数:
name: 日志记录器名称log: 日志文件路径level: 日志级别
gmt_date()
获取 GMT 格式的日期字符串。
date_str = gmt_date()
render_error()
渲染错误页面。
content = render_error(status_code, message)
参数:
status_code: HTTP 状态码message: 错误消息
返回:
错误页面内容
异常类
HttpError
HTTP 错误异常。
构造函数
HttpError(status_code, message)
参数:
status_code: HTTP 状态码message: 错误消息
示例
from litefs.exceptions import HttpError
def handler(self):
if not authenticated:
raise HttpError(401, 'Unauthorized')
return 'Success'
WSGI 接口
WSGIRequestHandler
WSGI 请求处理器。
构造函数
WSGIRequestHandler(app, environ)
参数:
app: Litefs 应用实例environ: WSGI 环境变量字典
属性
属性 |
类型 |
说明 |
|---|---|---|
|
dict |
WSGI 环境变量 |
|
str |
PATH_INFO |
|
str |
QUERY_STRING |
|
str |
REQUEST_METHOD |
|
str |
CONTENT_TYPE |
|
int |
CONTENT_LENGTH |
请求处理器
Request
请求对象,包含请求的所有信息。
属性
属性 |
类型 |
说明 |
|---|---|---|
|
dict |
WSGI 环境变量 |
|
str |
HTTP 方法(GET, POST, PUT, DELETE 等) |
|
str |
请求路径 |
|
str |
查询字符串 |
|
dict |
请求头 |
|
dict |
GET 参数(查询参数) |
|
dict |
POST 参数(表单数据) |
|
dict |
上传的文件 |
|
bytes |
原始请求体 |
|
dict |
路由路径参数 |
|
Session |
会话对象 |
|
str |
会话 ID |
示例
@get('/search', name='search')
def search_handler(request):
# 获取 GET 参数
query = request.params.get('query', '')
page = int(request.params.get('page', '1'))
# 获取 POST 参数
name = request.data.get('name')
email = request.data.get('email')
# 获取路由参数
user_id = request.route_params.get('id')
# 获取请求头
user_agent = request.headers.get('User-Agent')
# 获取原始请求体
raw_body = request.body
# 使用会话
request.session.set('user_id', 123)
user_id = request.session.get('user_id')
return {'query': query, 'page': page}
RequestHandler
请求处理器基类(传统文件系统路由)。
属性
属性 |
类型 |
说明 |
|---|---|---|
|
dict |
环境变量 |
|
Session |
会话对象 |
|
str |
会话 ID |
|
dict |
表单数据 |
|
Config |
配置对象 |
|
dict |
上传文件 |
|
SimpleCookie |
Cookie 数据 |
|
str |
PATH_INFO |
|
str |
QUERY_STRING |
|
str |
REQUEST_URI |
|
str |
REFERER |
|
str |
REQUEST_METHOD |
|
str |
SERVER_PROTOCOL |
方法
redirect()
重定向到指定 URL。
self.redirect(url)
参数:
url: 重定向 URL
start_response()
开始响应。
self.start_response(status_code=200, headers=None)
参数:
status_code: HTTP 状态码headers: 响应头部列表