Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Fast to Code gRPC in Python

License

NotificationsYou must be signed in to change notification settings

taogeYT/fast-grpc

Repository files navigation

🚀 Build gRPC services in Python 3.9+ as easily as FastAPI.

Installation

Require Python 3.9+

pip install python-fast-grpc

A Simple Example

Define a gRPC service:

frompydanticimportBaseModelfromfast_grpcimportFastGRPCapp=FastGRPC()classHelloRequest(BaseModel):name:strclassHelloReply(BaseModel):message:str@app.unary_unary()asyncdefsay_hello(request:HelloRequest)->HelloReply:returnHelloReply(message=f"Greeter SayHello{request.name}")if__name__=='__main__':app.run()

Client Test:

importgrpcimportfast_grpc_pb2aspb2importfast_grpc_pb2_grpcaspb2_grpcchannel=grpc.insecure_channel("127.0.0.1:50051")stub=pb2_grpc.FastGRPCStub(channel)response=stub.SayHello(pb2.HelloRequest(name="FastGRPC"))print("Client received: ",response)

Use Middleware

@app.middleware()asyncdefmiddleware(call_next,request,context):print("before request")response=awaitcall_next(request,context)print("after request")returnresponse@app.middleware(is_server_streaming=True)asyncdefmiddleware(call_next,request,context):print("before streaming request")asyncforresponseincall_next(request,context):yieldresponseprint("after streaming request")

Service

Use Service for modular design, similar to FastAPI's router.

fromfast_grpcimportServicesrv=Service(name="Greeter")@srv.unary_unary()asyncdefsay_again(request:HelloRequest)->HelloReply:returnHelloReply(message=f"Greeter SayHello{request.name}")

Pb2Service

Use Pb2Service if you're working with generated *_pb2.py and *_pb2_grpc.py files.

importgreeter_pb2importgreeter_pb2_grpcsrv=Pb2Service("Greeter",pb2_module=greeter_pb2,pb2_grpc_module=greeter_pb2_grpc)@srv.unary_unary()asyncdefsay_again(request:HelloRequest)->HelloReply:returnHelloReply(message=f"Greeter SayHello{request.name}")

Generate Clients Using Pydantic

Automatically generate a Pydantic-based gRPC client from .proto files:

fromfast_grpc.protoimportproto_to_python_clientproto_to_python_client("fast_grpc.proto")

[8]ページ先頭

©2009-2025 Movatter.jp