常规- tytx
轻量级多运量型数据交换系统.
TYTX取消了Python和JavaScript之间的手动类型转换,并让切换到MessagePack,以便像改变一个参数那样简单地实现更好的性能.
你送一个 Decimal 从Python, JavaScript 接收到一个字符串. 你把它转换回来。 每一个 单身. 时间 TYTX 在 Python 和 JavaScript 之间自动修正此类型, 超过 JSON, XML, 或 MessagePack .
你知道的痛苦
# Your Python API
return {"price": Decimal("99.99"), "due_date": date(2025, 1, 15)}
// Your JavaScript client
const data = await response.json();
// data.price is "99.99" (string) - need to convert
// data.due_date is "2025-01-15" (string) - need to convert
const price = new Decimal(data.price); // Manual conversion
const dueDate = new Date(data.due_date); // Manual conversion
这导致:
- 转换代码分散于各地
- 当有人忘记皈依时会出现虫子
- 有浮动点错误的财务计算
- 不同日期格式导致一天出错
TYTX 解决方案
# Server - just return native types
return {"price": Decimal("99.99"), "due_date": date(2025, 1, 15)}
// Client - types arrive ready to use
const data = await fetchTytx('/api/order');
data.price // → Decimal (not string)
data.due_date // → Date (not string)
零转换码. 类型只是工作.
30-二级民主
Python : (中文(简体) )
pip install genro-tytx
from decimal import Decimal
from datetime import date
from genro_tytx import to_tytx, from_tytx
# Encode
data = {"price": Decimal("99.99"), "date": date(2025, 1, 15)}
encoded = to_tytx(data)
# '{"price":"99.99::N","date":"2025-01-15::D"}::JS'
# Decode
decoded = from_tytx(encoded)
# {"price": Decimal("99.99"), "date": date(2025, 1, 15)}
Java 脚本 :
npm install @genrojs/tytx # npm
bunx jsr add @genro/tytx # JSR
import { fetchTytx } from '@genro/tytx';
import Big from 'big.js';
const result = await fetchTytx('/api/invoice', {
body: { price: new Big('99.99'), date: new Date() }
});
// result.total → Big (ready to use)
未键入的 JSON 编码器
除了键入 to_tytx 编号 : from_tytx API, TYTX 曝光了用于未打字路径的平面 JSON 编码器——没有类型后缀,只是快了 JSON (orjson 当可用时, stdlib 否则):
from genro_tytx import json_dumps, json_loads
json_dumps({"a": 1}) # -> b'{"a":1}' (UTF-8 bytes)
json_loads('{"a": 1}') # accepts str or bytes -> {"a": 1}
json_dumps 返回 UTF-8 bytes (准备ASGI/WebSocket发送), json_loads 接受 str 或者说 bytes。当您想要普通 JSON 时使用这些;使用 to_tytx 编号 : from_tytx 当您想要输入的数值流出时.
记录流(JSON线)
to_tytx_iter 编号 : from_tytx_iter (贾瓦脚本) toTytxIter 编号 : fromTytxIter)取一取一取一取一取一取一取一取一取一取一取一取还一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取一取 编码将输入的值转换为 "value::CODE" 无字符串 ::JS 每个记录都是普通的JSON,一个JSONL线. 解码使这些字符串重新变成被打入的值,并让其他一切保持不变. 同步源给出了活化器,活化源给出了活化器. 分流为行属于JSONL阅读器或编剧.
from genro_tytx import to_tytx_iter, from_tytx_iter
for record in to_tytx_iter(rows): # rows: dicts with Decimal, date, ...
out.write(json.dumps(record) + "\n") # {"price": "12.50::N", "day": "2026-10-22::D"}
for record in from_tytx_iter(json.loads(line) for line in open("orders.jsonl")):
... # record["price"] is a Decimal
async for record in from_tytx_iter(async_records): # async source -> async iterator
...
通过 HTTP 传输流为 Content-Type: application/jsonl 与 X-TYTX-Transport: jsonl· ; getTransport 返回时 'jsonl' 对于它。 结束早期的回复看起来像一个完整的回复:在信头后报告错误,或预期的记录数量取决于应用程序.
自定义类型
register_type 让外部包教 TYTX 一种新类型——在自定义后缀下串行化钩(object → string)和去区域化钩(string → object). 软件包在自己的导入时间注册,因此TYTX不会因此而获得依赖:
from genro_tytx import register_type, to_tytx, from_tytx
class Point:
def __init__(self, x, y): self.x, self.y = x, y
register_type(Point, "PT", lambda p: f"{p.x},{p.y}",
lambda s: Point(*map(int, s.split(","))))
to_tytx([1, Point(5, 6), "k"]) # '[1,"5,6::PT","k"]::JS'
from_tytx('5,6::PT') # Point(5, 6)
自定义类型会像任何内置的scalar一样流出,包括嵌入于dicts和列表中. 具体类型首先匹配;一个未注册的已注册类型子类按照该类型代码旅行,由它自己的序列器(genro-builders')编写 SourceBag 作为天才包子旅行 X),内置类型保持了精确类型规则. 一个阶级不能以另一个阶级拥有的代码注册. 一个代码是一个或多个大写 ASCII 字母,任意长度;注册拒绝其他任何内容. 重新登记同一类会取代其钩;重用由不同类型拥有的后缀会引起错误. 接收方的未知代码并非出错:字符串返回时未受影响. 同样的语义适用于JavaScript客户端(registerType 编号 : registerClass) (中文(简体) ). 消费者保留的规则和代码载于 spec/TYTX-SPEC.md 第2.5节.
当类型拥有它的序列化, register_class 读取来自类本身的钩子——可以用作装饰. 这需要 __tytx_suffix__,一个实例 to_tytx() (单位:千美元) from_tytx 类方法( c)from_tytx 必须是类方法: 解码从后缀开始, 从头重建实例 :
from genro_tytx import register_class
@register_class
class Point:
__tytx_suffix__ = "PT"
def __init__(self, x, y): self.x, self.y = x, y
def to_tytx(self): return f"{self.x},{self.y}"
@classmethod
def from_tytx(cls, s): return cls(*map(int, s.split(",")))
子类的混凝土类是该类型自己的业务. TYTX每个代码保存一个子类型词典,从未读取过: set_subtype_dict(suffix, dict) 替换它, get_subtype_dict(suffix) 返回( r){} 如果没有设定的话)。 Java 脚本 : setSubtypeDict 编号 : getSubtypeDict类型 to_tytx编号 :from_tytx 使用它; 添加子类调用者 register_subtype(suffix, cls, name=None) (贾瓦脚本) registerSubtype),它以自己的名称添加该类,或者在以下 name,如果名称已经属于另一类,则提出。 Genro -bag 地图符号名称的 Bag 类这种方式.
安装
# Python
pip install genro-tytx
# JavaScript/TypeScript, from npm
npm install @genrojs/tytx
# JavaScript/TypeScript, from JSR
bunx jsr add @genro/tytx
# With npm: npx jsr add @genro/tytx
JavaScript包括"十进制","大","MessagePack"和"XML"的依赖性. 无单独的 需要安装代码 。 Python额外项目保持不变.
真实世界实例:秩序处理
典型的业务情景:处理一个有8个打字字字的订单,返回6个打字结果.
1. 数据
JavaScript 客户端 有带有适当类型的命令数据 :
import Big from 'big.js';
const orderData = {
unit_price: new Big('149.99'), // Decimal
quantity: 3,
discount: new Big('10.00'), // Decimal
order_date: new Date(2025, 0, 15), // Date
delivery_date: new Date(2025, 0, 20),
express: true,
customer_id: 12345,
notes: 'Handle with care'
};
// Expects response: { subtotal, tax, shipping, total, ship_date, arrival_date }
Python 服务器 有商业逻辑期待合适的类型 :
async def process_order(unit_price, quantity, discount, order_date,
delivery_date, express, customer_id, notes):
"""Business logic - expects Decimal and date types."""
subtotal = unit_price * quantity
tax = subtotal * Decimal('0.22')
shipping = Decimal('15.00') if express else Decimal('5.00')
total = subtotal - discount + tax + shipping
ship_date = order_date + timedelta(days=1 if express else 3)
return {
'subtotal': subtotal, 'tax': tax, 'shipping': shipping,
'total': total, 'ship_date': ship_date, 'arrival_date': delivery_date
}
2. 没有TYTX:20个人工转换
Java 脚本 - 必须转换为/从字符串:
// Send: convert types → strings
const response = await fetch('/api/process_order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
unit_price: orderData.unit_price.toString(), // Decimal → string
discount: orderData.discount.toString(), // Decimal → string
order_date: orderData.order_date.toISOString().slice(0, 10), // Date → string
delivery_date: orderData.delivery_date.toISOString().slice(0, 10),
quantity: orderData.quantity, express: orderData.express,
customer_id: orderData.customer_id, notes: orderData.notes
})
});
// Receive: convert strings → types
const json = await response.json();
const result = {
subtotal: new Big(json.subtotal), tax: new Big(json.tax),
shipping: new Big(json.shipping), total: new Big(json.total),
ship_date: new Date(json.ship_date), arrival_date: new Date(json.arrival_date)
};
蟒 - 必须转换为/从字符串:
@app.post("/api/process_order")
async def handle_order(request: Request):
json_data = await request.json()
# Receive: convert strings → types
unit_price = Decimal(json_data['unit_price'])
discount = Decimal(json_data['discount'])
order_date = date.fromisoformat(json_data['order_date'])
delivery_date = date.fromisoformat(json_data['delivery_date'])
result = await process_order(unit_price, json_data['quantity'], discount,
order_date, delivery_date, json_data['express'],
json_data['customer_id'], json_data['notes'])
# Send: convert types → strings
return JSONResponse({
'subtotal': str(result['subtotal']), 'tax': str(result['tax']),
'shipping': str(result['shipping']), 'total': str(result['total']),
'ship_date': result['ship_date'].isoformat(),
'arrival_date': result['arrival_date'].isoformat()
})
共计:20个人工改划 (4个JS=字符串+4个字符串+Python+6个Python+字符串+6个字符串+JS).
3. 与TYTX:零转换
import { fetchTytx } from '@genro/tytx';
const result = await fetchTytx('/api/process_order', { body: orderData });
console.log(result.total.toFixed(2)); // Big, ready to use
共计:0个改划。 类型自然地流动.
奖励: 切换到一行中的信件包
要更好的性能需要二进制格式吗 ? 刚刚添加 transport: 'msgpack'数字 :
// JSON (default)
const result = await fetchTytx('/api/process_order', { body: orderData });
// MessagePack - same API, binary format
const result = await fetchTytx('/api/process_order', { body: orderData, transport: 'msgpack' });
支持类型
| 蟒 | Java 脚本 | 线条格式 |
|---|---|---|
Decimal | Decimal (大号.js) | "99.99::N" |
date | Date (协调世界时午夜) | "2025-01-15::D" |
datetime | Date | "2025-01-15T10:30:00.000Z::DHZ" |
time | Date (时代日期) | "10:30:00.000::H" |
bytes | Uint8Array | "AAEC::RAW" (base64;MessagePack上的本地文件夹) |
原生JSON类型(字符串,数字,布尔,无效)经过不变.
何时使用 TYTX
不错:
- 含有日期/ 十进制格式的 Web 应用程序
- 需要小数精确度的财务应用
- 经常发送/接收输入数据的API
- 混合类型类似 Excel 的网格
无需:
- 仅使用字符串和整数的 API
- 没有特殊类型的简单 CRUD
- 已使用全类型支持的 GraphQL/Protobuf
文档
| 我想... 说说看 I want to... | 继续... |
|---|---|
| 五分钟内试试看 | 快速启动 |
| 用在 HTTP 上 | HTTP 整合 |
| 理解线条格式 | 如何运作 |
| 见 API 参考 | API 参考 |
| 与替代品相比 | 替代品 |
许可证
Apache许可证2.0 - 版权2025 Softwell S.r.l.