Pure python approach of Apache Thrift(https://github.com/Thriftpy/thriftpy2.git)
数据类型(IDL)
基本类型
- bool: 布尔值 (true or false), one byte
- byte: 有符号字节
- i16: 16位有符号整型
- i32: 32位有符号整型
- i64: 64位有符号整型
- double: 64位浮点型
- string: 包括文本类型和二进制字符串
- void: 方法无返回值,可以定义返回类型为 void
容器类型
- list
: 元素类型为t1的有序表,容许元素重复 - set
:元素类型为t1的无序表,不容许元素重复 - map
: 键类型为t1,值类型为t2的kv对,键不容许重复
枚举类型
枚举可以指定每个元素的值,也可以不指定,默认从 0 开始递增
enum TweetType {
TWEET,
RETWEET = 2,
DM = 0xa,
REPLY
}
结构体
thrift 要求每个域都必须有一个唯一的正整数标识符,结构体可以包含其它结构体,可以指定默认值
struct Location {
1: required double latitude = 1.0;
2: required double longitude;
}
常量
const i32 INT_CONST = 1234;
其他
- namespace – 用于指定不同语言生成的目录结构
namespace cpp project namespace java com.example.project namespace php project
- include – 用于引用其他 idl 文件
include “tweet.thrift”
Thrift IDL
const i16 DEFAULT_LIST_SIZE = 10
typedef i32 timestamp
enum PhoneType {
MOBILE = 0,
HOME,
WORK,
}
struct PhoneNumber {
1: optional PhoneType type = PhoneType.MOBILE,
2: optional string number,
}
struct Person {
1: required string name,
2: optional list<PhoneNumber> phones,
3: optional timestamp created_at,
}
# 异常定义
exception PersonNotExistsError {
1: optional string message = "Person Not Exists!",
}
service PersonService {
bool add(1: required Person person);
bool remove(1: string name) throws (1: PersonNotExistsError not_exists);
Person get(1: string name) throws (1: PersonNotExistsError not_exists);
}
服务端
import asyncio
import thriftpy2
from thriftpy2.rpc import make_aio_server
echo_thrift = thriftpy2.load("echo.thrift", module_name="echo_thrift")
class Dispatcher(object):
async def echo(self, param):
print(param)
await asyncio.sleep(0.1)
return param
def main():
server = make_aio_server(
echo_thrift.EchoService, Dispatcher(), '127.0.0.1', 6000)
server.serve()
if __name__ == '__main__':
main()
客户端
同步
import thriftpy2
pingpong_thrift = thriftpy2.load("pingpong.thrift", module_name="pingpong_thrift")
from thriftpy2.rpc import make_client
client = make_client(pingpong_thrift.PingPong, '127.0.0.1', 6000)
print(client.ping())
异步
仅支持Python3.5以上
import thriftpy2
import asyncio
from thriftpy2.rpc import make_aio_client
echo_thrift = thriftpy2.load("echo.thrift", module_name="echo_thrift")
async def request():
client = await make_aio_client(
echo_thrift.EchoService, '127.0.0.1', 6000)
print(await client.echo('hello, world'))
client.close()