{"id":20619715,"url":"https://github.com/twtrubiks/grpc_python_tutorial","last_synced_at":"2026-05-07T07:38:55.036Z","repository":{"id":197352462,"uuid":"698481869","full_name":"twtrubiks/grpc_python_tutorial","owner":"twtrubiks","description":"grpc python 教學  Google RPC","archived":false,"fork":false,"pushed_at":"2023-10-04T14:02:24.000Z","size":7,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-17T05:09:08.839Z","etag":null,"topics":["grpc","python3","tutorial"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/twtrubiks.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-09-30T03:58:16.000Z","updated_at":"2023-11-06T07:10:22.000Z","dependencies_parsed_at":null,"dependency_job_id":"d8d26c1d-23cf-4471-9a61-581f64d0d5aa","html_url":"https://github.com/twtrubiks/grpc_python_tutorial","commit_stats":null,"previous_names":["twtrubiks/grpc_python_tutorial"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fgrpc_python_tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fgrpc_python_tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fgrpc_python_tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fgrpc_python_tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/twtrubiks","download_url":"https://codeload.github.com/twtrubiks/grpc_python_tutorial/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242277684,"owners_count":20101542,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["grpc","python3","tutorial"],"created_at":"2024-11-16T12:12:21.538Z","updated_at":"2026-05-07T07:38:55.030Z","avatar_url":"https://github.com/twtrubiks.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# grpc python 教學\n\n* [Youtube Tutorial - gRPC Python 基礎全攻略：掌握 Protobuf定義以及編譯、HTTP/2 高效能 RPC 開發](https://youtu.be/PBPKiPMxaQc)\n\ngRPC 也可以稱 Google RPC, 今天來用 python 把玩 😀\n\n## 介紹\n\n官網架構圖\n\n![alt tag](https://i.imgur.com/BeHImgV.png)\n\n簡單說，RPC (遠端程序呼叫) 就像你呼叫本機的 function 一樣。\n\n實際上，客戶端 (Client) 會透過一個由 `.proto` 文件編譯產生的「客戶端代理」(Client Stub) 來呼叫遠端函式,\n\n這個 Stub 看起來就像一個本地物件，它會幫你處理好參數打包、網路通訊等細節，\n\n讓你感覺就像直接呼叫本地函式 (實際上是呼叫遠端的函式).\n\n## 好處以及適合使用時機\n\n- 基於 HTTP/2 協定，支援多路復用、標頭壓縮、伺服器推送和雙向串流等特性，相比傳統 REST 具有更高的傳輸效率和更低的延遲\n\n- 原生串流支援 (Streaming), 相較 RESTful 如果要實現需要借助不同的機制或協定(WebSockets, Server-Sent Events (SSE) 或長輪詢等額外技術)\n\n- 預設使用 Protocol Buffers (Protobuf) 作為序列化格式。Protobuf 是二進位格式，傳輸效率高且輕量。`.proto` 文件具備**強型別**特性\n\n- 可從單一的 `.proto` 文件為多種主流程式語言（如 Python, Java, Go, C++, Node.js 等）自動生成類型安全的客戶端和伺服器端程式碼，極大地簡化了跨語言服務的開發與整合\n\n- 適合使用在微服務(microservices)內部溝通\n\n🧐 多路復用 (multiplexing)\n\n沒有多路復用 (類似 HTTP/1.1): 就像一條單線道的隧道。一次只能有一輛車（一個請求或回應）通過。如果前面的車開得慢（回應慢），後面的車就必須等待。如果想同時走更多車，就需要挖更多條獨立的隧道（建立多個 TCP 連接），但這樣成本很高（連接建立的開銷）。\n\n有多路復用 (類似 HTTP/2): 就像一條擁有多條車道的高速公路。雖然整條路（TCP 連接）只有一條，但上面可以同時容納來自不同起點、前往不同終點的多輛車（多個請求和回應）並行前進，它們在各自的車道（串流 Stream）上有序行駛，互不阻塞。\n\n## 環境安裝\n\n```cmd\npip install grpcio grpcio-tools\n```\n\n## 定義 proto\n\n第一步驟, 先定義 `proto`, 文檔路徑 [protos/user.proto](protos/user.proto)\n\n這裡面定義了 message 以及 service\n\n## 編譯\n\n第二步驟\n\n指令說明 (說明用, 不要使用這個指令, 原因後面說明)\n\n``` cmd\npython -m grpc_tools.protoc -I./protos --python_out=. --pyi_out=. --grpc_python_out=. ./protos/user.proto\n```\n\n`-I` or `--proto_path` 指定一個目錄，作為 Protocol Buffer 編譯器 (protoc) 搜尋 `.proto` 定義檔路徑.\n\n`--python_out=.` `--pyi_out=.` `--grpc_python_out=.` 這裡的意思都是放在當前目錄底下,\n\n我們統一把編譯出來的放到 `service_protos` 資料夾底下 (方便管理).\n\n指令範例\n\n(推薦使用以下指令進行編譯，利用路徑映射將生成檔案輸出到獨立的 `service_protos` 目錄並解決 `import` 問題)\n\n```cmd\npython -m grpc_tools.protoc -Iservice_protos=./protos --python_out=. --pyi_out=. --grpc_python_out=. ./protos/user.proto\n```\n\n說明 `-Iservice_protos=./protos`\n\n`service_protos` 這將成為生成程式碼中 import 路徑的一部分.\n\n可參考 [user_pb2_grpc.py](service_protos/user_pb2_grpc.py) 底下\n\n```python\n......\nfrom service_protos import user_pb2 as service__protos_dot_user__pb2\n......\n```\n\n可參考 [Generating gRPC interfaces with custom package path](https://grpc.io/docs/languages/python/basics/#generating-grpc-interfaces-with-custom-package-path)\n\n## grpc server\n\n第三步驟\n\n✍ server 和 client 都需要編譯後的檔案.\n\n先開啟一個 terminal 執行 server\n\n```cmd\n❯ python3 server.py\nServer started, listening on 50051\n```\n\n## grpc client\n\n✍ server 和 client 都需要編譯後的檔案.\n\n再開啟一個 terminal 執行 client\n\n```cmd\n❯ python3 client.py\n\ndetails {\n  id: 2\n  value: \"twtrubiks\"\n}\n```\n\n## grpc interceptor\n\n幫助你更好的管理 grpc log\n\n```cmd\npip install grpc-interceptor\n```\n\n在 [server.py](server.py) 中, 加入底下 code\n\n```python\n......\ninterceptors = [ExceptionToStatusInterceptor()]\nserver = grpc.server(\n        concurrent.futures.ThreadPoolExecutor(max_workers=10),\n        interceptors=interceptors\n    )\n......\n```\n\n如果你加上這個, 當發生錯誤你會更快的找到問題\n\n加入前\n\n![alt tag](https://i.imgur.com/9rgEXjK.png)\n\n加入後\n\n![alt tag](https://i.imgur.com/82XaPdV.png)\n\n## 官方範例\n\n如果你還需要範例可參考 [https://github.com/grpc/grpc/tree/v1.72.0/examples/python](https://github.com/grpc/grpc/tree/v1.72.0/examples/python)\n\n## Reference\n\n* [https://grpc.io/docs/what-is-grpc/introduction/](https://grpc.io/docs/what-is-grpc/introduction/)\n\n* [https://grpc.io/docs/languages/python/basics/](https://grpc.io/docs/languages/python/basics/)\n\n* [https://grpc-interceptor.readthedocs.io/en/latest/](https://grpc-interceptor.readthedocs.io/en/latest/)\n\n## Donation\n\n文章都是我自己研究內化後原創，如果有幫助到您，也想鼓勵我的話，歡迎請我喝一杯咖啡:laughing:\n\n綠界科技ECPAY ( 不需註冊會員 )\n\n![alt tag](https://payment.ecpay.com.tw/Upload/QRCode/201906/QRCode_672351b8-5ab3-42dd-9c7c-c24c3e6a10a0.png)\n\n[贊助者付款](https://bit.ly/2F7Jrha)\n\n歐付寶 ( 需註冊會員 )\n\n![alt tag](https://i.imgur.com/LRct9xa.png)\n\n[贊助者付款](https://payment.opay.tw/Broadcaster/Donate/9E47FDEF85ABE383A0F5FC6A218606F8)\n\n## 贊助名單\n\n[贊助名單](https://github.com/twtrubiks/Thank-you-for-donate)\n\n## License\n\nMIT license","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwtrubiks%2Fgrpc_python_tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftwtrubiks%2Fgrpc_python_tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwtrubiks%2Fgrpc_python_tutorial/lists"}