Skip to content

chclock/libra

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Libra 框架

Libra 是一个极简的 Python Web 框架,仿照 Flask 开发,用于构建轻量级的 RESTful API 应用。

特性

  • WSGI 兼容:可配合 Gunicorn、uWSGI 等 WSGI 服务器运行
  • 路由系统:装饰器方式定义路由,支持 URL 参数
  • 请求/响应对象:便捷获取请求数据,构建响应
  • 模板渲染:支持简单的模板语法
  • 异常处理:内置常见的 HTTP 异常类

安装

pip install -e .

快速开始

# app.py
from libra import Libra

app = Libra()


@app.route('/hello')
def hello():
    return 'Hello, World!'


@app.route('/user/<id>')
def get_user(id):
    return {'id': id, 'name': f'User {id}'}


if __name__ == '__main__':
    app.run()

运行:

python app.py

访问 http://127.0.0.1:5000/hello

路由

基本路由

@app.route('/path')
def view_function():
    return 'Response'

HTTP 方法

@app.get('/items')      # GET 请求
def get_items():
    return items

@app.post('/items')     # POST 请求
def create_item():
    return 'Created', 201

@app.put('/items/<id>')    # PUT 请求
def update_item(id):
    return f'Updated {id}'

@app.delete('/items/<id>') # DELETE 请求
def delete_item(id):
    return f'Deleted {id}'

URL 参数

# 字符串参数(默认)
@app.route('/user/<name>')
def get_user(name):
    return f'User: {name}'

# 整数参数
@app.route('/post/<id:int>')
def get_post(id):
    return f'Post ID: {id}'

# 路径参数(包含斜杠)
@app.route('/files/<path:filepath>')
def get_file(filepath):
    return f'File: {filepath}'

请求对象

from libra import Libra, Request

app = Libra()


@app.route('/request-demo')
def handle_request(request: Request):
    # 获取请求方法
    method = request.method

    # 获取 URL 参数
    args = request.args  # 返回字典

    # 获取 JSON 数据
    json_data = request.json  # 返回字典或 None

    # 获取表单数据
    form_data = request.form  # 返回字典

    # 获取请求头
    headers = request.headers

    # 获取客户端 IP
    ip = request.remote_addr

    return {
        'method': method,
        'args': args,
    }

响应对象

from libra import Libra, Response

app = Libra()


# 直接返回字符串
@app.route('/hello')
def hello():
    return 'Hello!'


# 返回字典(自动转为 JSON)
@app.route('/json')
def json_resp():
    return {'message': 'ok', 'count': 10}


# 使用 Response 对象
@app.route('/custom')
def custom_response():
    response = Response('Custom response')
    response.set_header('X-Custom', 'value')
    return response


# 使用 Response 工厂方法
@app.route('/jsonify')
def json_response():
    return Response.jsonify({'data': [1, 2, 3]})


# 重定向
@app.route('/old')
def old_url():
    return Response.redirect('/new', status=301)

模板渲染

from libra import Libra, render_template

app = Libra()


@app.route('/template')
def show_template():
    return render_template('Hello {{ name }}!', name='World')


# 循环示例
@app.route('/list')
def show_list():
    items = ['Apple', 'Banana', 'Orange']
    return render_template(
        '{% for item in items %}{{ item }}{% endfor %}',
        items=items
    )

钩子函数

from libra import Libra

app = Libra()


# 请求前执行
@app.before_request
def check_auth():
    # 返回非 None 值会终止请求
    return 'Unauthorized'


# 请求后执行
@app.after_request
def add_header(response):
    response.set_header('X-Powered-By', 'Libra')
    return response

运行服务器

开发模式

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

生产模式(使用 Gunicorn)

gunicorn -w 4 -b 0.0.0.0:5000 app:app

异常处理

from libra import Libra, NotFoundError, BadRequestError

app = Libra()


@app.route('/user/<id>')
def get_user(id):
    if not id.isdigit():
        raise BadRequestError('Invalid ID')
    # ... 业务逻辑

项目结构

myapp/
├── app.py              # 主应用
├── requirements.txt    # 依赖
└── views/              # 视图函数(可选)
    └── api.py

依赖

  • Python 3.8+

许可证

MIT License

About

Libra web

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages