Bali集成了 FastAPI 和 gRPC 的框架
Bali 基于 FastAPI 和 gRPC,简化了云原生微服务开发。如果你想让你的项目同时支持 HTTP 和 gRPC ,那么 Bali 可以帮助你很轻松的完成。
Bali 的特性:
* 项目结构简单。
* 融合了 `SQLAlchemy` 并提供了 model 生成的方法。
* 提供了工具类转换 model 成为 Pydantic 模式.
* 支持 GZip 解压缩.
* 🍻 **Resource** 层处理对外服务即支持 HTTP 又支持 gRPC
谁在使用
依赖项:
1. Python 3.8+
2. FastAPI 0.63+
3. grpcio>=1.32.0,<1.42
安装:
pip install bali-core
创建应用:
import greeter_server
# Initialized App
app = Bali()
# Updated settings
app.settings(base_settings={'title': 'Bali App'})
启动 HTTP & RPC:
# lauch RPC
python main.py --rpc
# lauch HTTP
python main.py --http
数据库对象的使用:
### connect
from bali.core import db
# connect to database when app started
# db is a sqla-wrapper instance
db.connect('DATABASE_URI')
### Declarative mode with sqla-wrapper
class User(db.Model):
__tablename__ "users"
id = db.Column(db.Integer, primary_key=True)
...
db.create_all()
db.add(User(...))
db.commit()
todos = db.query(User).all()
### Declare models inherit from convenient base models
## BaseModel
# using BaseModel
class User(db.BaseModel):
__tablename__ "users"
id = db.Column(db.Integer, primary_key=True)
# BaseModel's source code
class BaseModel(db.Model):
__abstract__ = True
created_time = Column(DateTime(timezone=True), default=datetime.utcnow)
updated_time = Column(
DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow
)
is_active = Column(Boolean(), default=True)
### Transaction
# SQLA-wrapper default model behavior is auto commit, auto commit will be disabled with `db.transaction` context.
with db.transaction():
item = Item.create(name='test1')
### Operators
# Operators provided `get_filters_expr` to transform filters (dict) to SQLAlchemy expressions.
from bali.db.operators import get_filters_expr
from models import User
users = User.query().filter(*get_filters_expr(User, **filters)).all()
Resource
资源(Resouce)的设计借鉴了REST架构风格的几个关键概念。HTTP 和 RPC 使用的是同一套 Resouce 代码,常用的 action 的对应关系如下:
Action | Route | Method | RPC | Description |
---|---|---|---|---|
get | /{id} | GET | Get{Resource} | Get an existing resource matching the given id |
list | / | GET | List{Resource} | Get all the resources |
create | / | POST | Create{Resource} | Create a new resource |
update | /{id} | PATCH | Update{Resource} | Update an existing resource matching the given id |
delete | /{id} | DELETE | Delete{Resource} | Delete an existing resource matching the given id |
缓存的使用:
from bali.core import cache
# Usage example (API)
# Read cache
cache.get(key)
# Set cache
cache.set(key, value, timeout=10)
评论