This guide gets you started with gRPC in Python with a simple working example.
Python 3.5 or higher
pip version 9.0.1 or higher
gRPC 설치
$ python -m pip install grpcio
Python의 gRPC 도구에는 프로토콜 버퍼 컴파일러 protoc
와 .proto
서비스 정의에서 서버 및 클라이언트 코드를 생성하기 위한 특수 플러그인이 포함됩니다.
빠른 시작 예제의 첫 번째 부분에서는 이미 helloworld.proto에 서버 및 클라이언트 스텁을 생성했지만 나머지에서 빠른 시작을 위한 도구와 이후 자습서 및 자체 프로젝트가 필요합니다.
gPRC tools를 설치하기 위해,
$ python -m pip install grpcio-tools
이 빠른 시작을 진행하려면 예제 코드의 로컬 사본이 필요합니다.
GitHub 리포지토리에서 예제 코드를 다운로드합니다.
(다음 명령은 전체 리포지토리를 복제하지만이 빠른 시작 및 기타 자습서에 대한 예제만 필요함)
# Clone the repository to get the example code:
$ git clone -b v1.34.1 https://github.com/grpc/grpc
# Navigate to the "hello, world" Python example:
$ cd grpc/examples/python/helloworld
examples/python/helloworld
폴더에서
$ python greeter_server.py
$ python greeter_client.py
축하합니다! gRPC로 클라이언트-서버 애플리케이션을 실행했습니다.
이제 클라이언트가 호출 할 수 있도록 서버에서 추가 메서드를 사용하여 애플리케이션을 업데이트하는 방법을 살펴 보겠습니다.
gRPC 서비스는 프로토콜 버퍼를 사용하여 정의됩니다.(gRPC 소개 및 기본 사항 가이드에서 .proto
파일에서 서비스를 정의하는 방법에 대해 자세히 알아볼 수 있습니다.)
지금 당장 알아야 할 것은 서버와 클라이언트 "stub" 모두 클라이언트에서 HelloRequest
매개 변수를 가져와 서버에서 HelloReply
를 반환하는 SayHello
RPC 메서드가 있으며 이 메서드는 다음과 같이 정의된다는 것입니다.
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
Greeter
서비스에 두 가지 방법이 있도록 업데이트하겠습니다.
examples/protos/helloworld.proto
를 편집하고 동일한 요청 및 응답 유형으로 새 SayHelloAgain
메서드로 업데이트합니다.
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
다음으로 새로운 서비스 정의를 사용하기 위해 애플리케이션에서 사용하는 gRPC 코드를 업데이트해야합니다.
examples/python/helloworld
폴더에서 다음을 실행하십시오.
$ python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/helloworld.proto
그러면 생성된 요청 및 응답 클래스가 포함 된 helloworld_pb2.py
와 생성 된 클라이언트 및 서버 클래스가 포함 된 helloworld_pb2_grpc.py
가 다시 생성됩니다.
이제 새로 생성 된 서버 및 클라이언트 코드가 있지만 예제 애플리케이션의 사람이 작성한 부분에서 새 메서드를 구현하고 호출해야합니다.
같은 폴더에서 greeter_server.py
를 엽니다. 다음과 같은 새 메소드를 구현하십시오.
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def SayHelloAgain(self, request, context):
return helloworld_pb2.HelloReply(message='Hello again, %s!' % request.name)
...
같은 폴더에서 greeter_client.py
를 엽니다. 다음과 같이 새 메서드를 호출합니다.
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message)
response = stub.SayHelloAgain(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message)
이전과 마찬가지로 examples/python/helloworld
폴더에서,
$ python greeter_server.py
$ python greeter_client.py