Skip to content

Latest commit

 

History

History
161 lines (115 loc) · 3.21 KB

File metadata and controls

161 lines (115 loc) · 3.21 KB

快速开始

安装

pip install litefs

或从源码安装:

git clone https://github.com/leafcoder/litefs.git
cd litefs
pip install -r requirements.txt
python setup.py install

基本示例

使用装饰器风格

from 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.py

独立示例文件

  • asgi_example.py - ASGI 示例

WSGI 部署

创建 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

下一步