python 使用gRPC


Python gRPC

  • 簡介
    grpc 是google 開源的一款rpc服務框架,可以輕松的實現跨語言的微服務,將項目中的各個模塊獨立出來,單獨部署,獨立升級,也可以根據模塊的情況進行不同語言的變成。
    gRPC也是一個C/S框架,使用的是HTTP2 協議進行通信。

  • 准備.proto文件

  syntax = "proto3";
  
  package order;
  message OrderRequest {
      string phone = 1;
      string price = 2;
      map<string, string> request_arg = 3;//便於字段擴展
  }

 message JSONResponse{
     string rst_string = 1; //統一返回json字符串作處理
     }

  service OrderHandler {
    // format a list of events.
    rpc create_order (OrderRequest) returns (JSONResponse) {}
 }

其中:

message: 定義數據結構

service: 定義接口的名字,參數,

  • 生成所需文件(服務器和客戶端均需要)
python -m grpc_tools.protoc -I./ --python_out=./ --grpc_python_out=./ ./*.proto
  • 編寫server端代碼
 import time
 import test_pb2_grpc
 import grpc

 from concurrent import futures
 from order.views import test
 
 import os

 class OrderHandler(test_pb2_grpc.OrderHandlerServicer):
     def create_order(self, request, context):
         return test(request, context)

 def serve():
     server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
     test_pb2_grpc.add_OrderHandlerServicer_to_server(
     										OrderHandler(), server)
     server.add_insecure_port('[::]:{}'.format(12006))
     server.start()
     try:
         while True:
             time.sleep(186400)
     except KeyboardInterrupt:
         server.stop(0)
serve()
  • 對應的views.py 文件
 from django.shortcuts import render
 from django.http import JsonResponse
 # Create your views here.
 import test_pb2
 import json
 from django.http import HttpRequest

 def grpc_request(func):
     “”“
     將grpc請求重新構造成django requst, 
     並封裝相應返回值
     ”“”
     def f(request, context):
         f = lambda x:{k:v for k,v in x.items()} if hasattr(x, 'items') else x
         args = {i[0].name:f(i[1]) for i in request.ListFields() }
         
         # 構造django request 對象,並添加參數信息
         dj_request = HttpRequest()
         dj_request.GET = args
         # dj_request.POST = args
         # dj_request._body = json.dumps(args)
         dj_request.META = args

         ret = func(dj_request)
         
         # 處理django的response 對象, 轉換為grpc的對象
         json_response = test_pb2.JSONResponse()
         json_response.rst_string = ret.getvalue()
         
         return json_response
     return f

 def check_inenty(func):
     def f(request):
         if "identy" not in request.META:
             return JsonResponse(dict(status=403))
         else:
             return func(request)
     return f

 @grpc_request
 @check_inenty
 def test(request):
     return JsonResponse(dict(test=1, name="333"))
  • 編寫客戶端代碼進行 測試 client.py
 import grpc
 import test_pb2_grpc
 import test_pb2

 channel = grpc.insecure_channel("127.0.0.1:12006")
 stub = test_pb2_grpc.OrderHandlerStub(channel)
 ret = stub.create_order(test_pb2.OrderRequest(phone="12990", price="50"))
 
 print(ret.rst_string)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM