python GRPC的官網(wǎng)示例

環(huán)境

windows 10 + Python 3.7

相關(guān)依賴包:

image.png
>pip install grpcio-tools
>pip install protobuf
>pip install grpcio

錯(cuò)誤問題:

C:\Users\mayn\.virtualenvs\dfgd\Scripts\python.exe: Error while finding module specification for 'grpc_tools.protoc' (ModuleNotFoundError: No module named 'grpc_tools')

上述錯(cuò)誤是因?yàn)槲覀兊臎]安裝:grpcio-tools

項(xiàng)目示例

示例來源:http://www.reibang.com/p/9c947d98e192

image.png

調(diào)用流程圖示:


image.png
  • 步驟1:新建項(xiàng)目含友,通過protobuf定義接口和數(shù)據(jù)類型粘姜,創(chuàng)建存在user_info.proto文件夾
  • 步驟2:新建rpc_package python包,然后根據(jù)proto文件生成對(duì)應(yīng)文件
    命令:
python -m grpc_tools.protoc -I=./protos --python_out=./rpc_package --grpc_python_out=./rpc_package ./protos/helloworld.proto

結(jié)果:

(dfgd) D:\code\python\local_python\dfgd>python -m grpc_tools.protoc -I=./protos --python_out=./rpc_package --grpc_python_out=./rpc_package ./protos/helloworld.proto

改寫一下我們的生產(chǎn)的文件击孩,導(dǎo)入的時(shí)候錯(cuò)誤問題:


image.png
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc


# import helloworld_pb2 as helloworld__pb2
from .helloworld_pb2 import HelloRequest,HelloReply

class HelloWorldServiceStub(object):
    """define a service
    """

    def __init__(self, channel):
        """Constructor.

        Args:
            channel: A grpc.Channel.
        """
        self.SayHello = channel.unary_unary(
                '/rpc_package.HelloWorldService/SayHello',
                request_serializer=HelloRequest.SerializeToString,
                response_deserializer=HelloReply.FromString,
                )


class HelloWorldServiceServicer(object):
    """define a service
    """

    def SayHello(self, request, context):
        """define the interface and data type
        """
        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
        context.set_details('Method not implemented!')
        raise NotImplementedError('Method not implemented!')


def add_HelloWorldServiceServicer_to_server(servicer, server):
    rpc_method_handlers = {
            'SayHello': grpc.unary_unary_rpc_method_handler(
                    servicer.SayHello,
                    request_deserializer=HelloRequest.FromString,
                    response_serializer=HelloReply.SerializeToString,
            ),
    }
    generic_handler = grpc.method_handlers_generic_handler(
            'rpc_package.HelloWorldService', rpc_method_handlers)
    server.add_generic_rpc_handlers((generic_handler,))


 # This class is part of an EXPERIMENTAL API.
class HelloWorldService(object):
    """define a service
    """

    @staticmethod
    def SayHello(request,
            target,
            options=(),
            channel_credentials=None,
            call_credentials=None,
            insecure=False,
            compression=None,
            wait_for_ready=None,
            timeout=None,
            metadata=None):
        return grpc.experimental.unary_unary(request, target, '/rpc_package.HelloWorldService/SayHello',
            HelloRequest.SerializeToString,
            HelloReply.FromString,
            options, channel_credentials,
            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)

  • 步驟3:編寫gRPC server服務(wù)端代碼 gfgd_grpc_server.py
#!/usr/bin/evn python
# coding=utf-8
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +
#        ┏┓   ┏┓+ +
#    ┏┛┻━━━┛┻┓ + +
#    ┃       ┃  
#    ┃   ━   ┃ ++ + + +
#    ████━████ ┃+
#    ┃       ┃ +
#    ┃   ┻   ┃
#    ┃       ┃ + +
#    ┗━┓   ┏━┛
#      ┃   ┃           
#      ┃   ┃ + + + +
#      ┃   ┃    Codes are far away from bugs with the animal protecting   
#      ┃   ┃ +     神獸保佑,代碼無bug  
#      ┃   ┃
#      ┃   ┃  +         
#      ┃    ┗━━━┓ + +
#      ┃        ┣┓
#      ┃        ┏┛
#      ┗┓┓┏━┳┓┏┛ + + + +
#       ┃┫┫ ┃┫┫
#       ┗┻┛ ┗┻┛+ + + +
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +"""
"""
# 版權(quán)說明
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +

# @Time  : 2021/2/2 11:43

# @Author : mayn

# @Project : dfgd

# @FileName: gfgd_grpc_server.py

# @Software: PyCharm

# 作者:小鐘同學(xué)

# 著作權(quán)歸作者所有

# 文件功能描述:
"""

from concurrent import futures
import grpc
import logging
import time

from rpc_package.helloworld_pb2_grpc import add_HelloWorldServiceServicer_to_server,HelloWorldServiceServicer
from rpc_package.helloworld_pb2 import HelloRequest, HelloReply


class Hello(HelloWorldServiceServicer):

    # 這里實(shí)現(xiàn)我們定義的接口
    def SayHello(self, request, context):
        return HelloReply(message='Hello, %s!' % request.name)


def serve():
    # 這里通過thread pool來并發(fā)處理server的任務(wù)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

    # 將對(duì)應(yīng)的任務(wù)處理函數(shù)添加到rpc server中
    add_HelloWorldServiceServicer_to_server(Hello(), server)

    # 這里使用的非安全接口,世界gRPC支持TLS/SSL安全連接匆浙,以及各種鑒權(quán)機(jī)制
    server.add_insecure_port('[::]:50000')
    server.start()
    try:
        while True:
            time.sleep(60 * 60 * 24)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == "__main__":
    logging.basicConfig()
    serve()
  • 步驟4:編寫gRPC client調(diào)用端代碼 dfgd_grpc_clien.py
#!/usr/bin/evn python
# coding=utf-8
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +
#        ┏┓   ┏┓+ +
#    ┏┛┻━━━┛┻┓ + +
#    ┃       ┃  
#    ┃   ━   ┃ ++ + + +
#    ████━████ ┃+
#    ┃       ┃ +
#    ┃   ┻   ┃
#    ┃       ┃ + +
#    ┗━┓   ┏━┛
#      ┃   ┃           
#      ┃   ┃ + + + +
#      ┃   ┃    Codes are far away from bugs with the animal protecting   
#      ┃   ┃ +     神獸保佑,代碼無bug  
#      ┃   ┃
#      ┃   ┃  +         
#      ┃    ┗━━━┓ + +
#      ┃        ┣┓
#      ┃        ┏┛
#      ┗┓┓┏━┳┓┏┛ + + + +
#       ┃┫┫ ┃┫┫
#       ┗┻┛ ┗┻┛+ + + +
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +"""
"""
# 版權(quán)說明
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +

# @Time  : 2021/2/2 11:44

# @Author : mayn

# @Project : dfgd

# @FileName: dfgd_grpc_clien.py

# @Software: PyCharm

# 作者:小鐘同學(xué)

# 著作權(quán)歸作者所有

# 文件功能描述: 
"""

from __future__ import print_function
import logging

import grpc
from rpc_package.helloworld_pb2 import HelloRequest, HelloReply
from rpc_package.helloworld_pb2_grpc import HelloWorldServiceStub

def run():
    # 使用with語法保證channel自動(dòng)close
    with grpc.insecure_channel('localhost:50000') as channel:
        # 客戶端通過stub來實(shí)現(xiàn)rpc通信
        stub = HelloWorldServiceStub(channel)

        # 客戶端必須使用定義好的類型刃泌,這里是HelloRequest類型
        response = stub.SayHello(HelloRequest(name='eric'))
    print ("hello client received: " + response.message)

if __name__ == "__main__":
    logging.basicConfig()
    run()

啟動(dòng)相關(guān)服務(wù)端服務(wù)和客戶端:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市勺远,隨后出現(xiàn)的幾起案子橙喘,更是在濱河造成了極大的恐慌,老刑警劉巖胶逢,帶你破解...
    沈念sama閱讀 216,843評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件厅瞎,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡初坠,警方通過查閱死者的電腦和手機(jī)和簸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來碟刺,“玉大人锁保,你說我怎么就攤上這事“牍粒” “怎么了爽柒?”我有些...
    開封第一講書人閱讀 163,187評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)者填。 經(jīng)常有香客問我浩村,道長(zhǎng),這世上最難降的妖魔是什么占哟? 我笑而不...
    開封第一講書人閱讀 58,264評(píng)論 1 292
  • 正文 為了忘掉前任穴亏,我火速辦了婚禮蜂挪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘嗓化。我一直安慰自己棠涮,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,289評(píng)論 6 390
  • 文/花漫 我一把揭開白布刺覆。 她就那樣靜靜地躺著严肪,像睡著了一般。 火紅的嫁衣襯著肌膚如雪谦屑。 梳的紋絲不亂的頭發(fā)上驳糯,一...
    開封第一講書人閱讀 51,231評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音氢橙,去河邊找鬼酝枢。 笑死,一個(gè)胖子當(dāng)著我的面吹牛悍手,可吹牛的內(nèi)容都是我干的帘睦。 我是一名探鬼主播,決...
    沈念sama閱讀 40,116評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼坦康,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼竣付!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起滞欠,我...
    開封第一講書人閱讀 38,945評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤古胆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后筛璧,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體逸绎,經(jīng)...
    沈念sama閱讀 45,367評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,581評(píng)論 2 333
  • 正文 我和宋清朗相戀三年夭谤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了桶良。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,754評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡沮翔,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出曲秉,到底是詐尸還是另有隱情采蚀,我是刑警寧澤,帶...
    沈念sama閱讀 35,458評(píng)論 5 344
  • 正文 年R本政府宣布承二,位于F島的核電站榆鼠,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏亥鸠。R本人自食惡果不足惜妆够,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,068評(píng)論 3 327
  • 文/蒙蒙 一识啦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧神妹,春花似錦颓哮、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蛹找,卻和暖如春姨伤,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背庸疾。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工乍楚, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人届慈。 一個(gè)月前我還...
    沈念sama閱讀 47,797評(píng)論 2 369
  • 正文 我出身青樓徒溪,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親拧篮。 傳聞我的和親對(duì)象是個(gè)殘疾皇子词渤,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,654評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容