pip install litefs或从源码安装:
git clone https://github.com/leafcoder/litefs.git
cd litefs
pip install -r requirements.txt
python setup.py installfrom litefs import Litefs
from litefs.routing import get, post
app = Litefs(
host='0.0.0.0',
port=8080,
debug=True
)
@get('/', name='index')
def index_handler(request):
return 'Hello, World!'
@get('/user/{id}', name='user_detail')
def user_detail_handler(request, id):
return f'User ID: {id}'
@post('/login', name='login')
def login_handler(request):
username = request.data.get('username')
password = request.data.get('password')
return {'status': 'success', 'username': username}
app.register_routes(__name__)
app.run()Litefs 会根据返回值类型自动设置 Content-Type 响应头:
| 返回值类型 | Content-Type |
|---|---|
dict / list / tuple |
application/json; charset=utf-8 |
HTML 字符串(以 < 开头) |
text/html; charset=utf-8 |
bytes |
application/octet-stream |
| 其他类型 | text/html; charset=utf-8(默认) |
示例:
@get('/api/user')
def get_user(request):
# 自动设置 Content-Type: application/json
return {'id': 1, 'name': 'Alice'}
@get('/page')
def get_page(request):
# 自动设置 Content-Type: text/html
return '<html><body>Hello</body></html>'
@get('/download')
def download(request):
# 自动设置 Content-Type: application/octet-stream
return b'\x00\x01\x02\x03'也可以手动设置响应头:
@get('/custom')
def custom_response(request):
request.start_response(200, [('Content-Type', 'text/plain; charset=utf-8')])
return 'Custom content type'from litefs import Litefs
app = Litefs()
def index_handler(request):
return 'Hello, World!'
def user_detail_handler(request, id):
return f'User ID: {id}'
app.add_get('/', index_handler, name='index')
app.add_get('/user/{id}', user_detail_handler, name='user_detail')
app.run()Litefs 提供了丰富的示例代码,位于 examples/ 目录:
01-hello-world/- 快速入门示例02-routing/- 路由系统示例03-blog/- 博客应用示例04-api-service/- API 服务示例05-fullstack/- 完整应用示例06-sqlalchemy/- SQLAlchemy 集成示例07-streaming/- 流式响应示例08-comprehensive/- 综合示例(推荐新手)
运行方式:
cd examples/01-hello-world
python app.pyasgi_example.py- ASGI 示例
创建 wsgi.py:
from litefs import Litefs
app = Litefs()
@get('/', name='index')
def index_handler(request):
return 'Hello, World!'
application = app.wsgi()使用 Gunicorn:
gunicorn -w 4 -b :8000 wsgi:application