02.grpc_flask
# 01.grpc-flask-test项目说明
# 1.1 项目结构
# 1.2 运行项目
- 生成 protoc文件
# 指定文件夹生成
cd protos
python3 -m grpc_tools.protoc -Iprotos --python_out=compiles --grpc_python_out=compiles protos/recommendations.proto
1
2
3
2
3
安装包
python3 -m pip install -r requirements.txt
- `启动grpc 服务端`
```bash
cd grpc-server
python3 server.py
# server will start localhost:50051
1
2
3
4
5
6
7
2
3
4
5
6
7
启动 grpc客户端
cd grpc-client
python3 app.py
# flask server will start ```localhost:5000```
1
2
3
2
3
- http://127.0.0.1:5000/ 谷歌浏览器
{
"recommendations": [
{
"id": 1,
"title": "The Maltese Falcon"
},
{
"id": 3,
"title": "The Hound of the Baskervilles"
},
{
"id": 2,
"title": "Murder on the Orient Express"
}
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 02.项目文件
# 2.1 protos/recommendations.proto
cd protos python3 -m grpc_tools.protoc -Iprotos --python_out=compiles --grpc_python_out=compiles protos/recommendations.proto
1
2
syntax = "proto3";
enum BookCategory {
MYSTERY = 0;
SCIENCE_FICTION = 1;
SELF_HELP = 2;
}
message RecommendationsRequest {
int32 user_id = 1;
BookCategory category = 2;
int32 max_results = 3;
}
message BookRecommendations {
int32 id = 1;
string title = 2;
}
message RecommendationsResponse {
repeated BookRecommendations recommendations = 1;
}
service Recommendations {
rpc Recommend (RecommendationsRequest) returns (RecommendationsResponse) {}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 2.2 grpc服务端
# 2.2.1 grpc-server/server.py
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
import time
import grpc
import random
import logging
from signal import signal, SIGTERM, SIGINT
from concurrent import futures
from recommendations import books_by_category
from protos.recommendations import recommendations_pb2, recommendations_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class RecommendationsService(recommendations_pb2_grpc.RecommendationsServicer):
def Recommend(self, request, context):
# books_by_category --> 模拟从数据库取数据
if request.category not in books_by_category:
context.abort(grpc.StatusCode.NOT_FOUND, "Category not found")
books_for_category = books_by_category[request.category]
num_results = min(request.max_results, len(books_for_category))
books_to_recommend = random.sample(books_for_category, num_results)
return recommendations_pb2.RecommendationsResponse(recommendations=books_to_recommend)
# Server setup and starting
def serve():
# 通过并发库,将服务端放到多进程池里运行
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
# add_XxxServicer_to_server用于把实现的类和grpcAPI调用注册起来
recommendations_pb2_grpc.add_RecommendationsServicer_to_server(RecommendationsService(), server)
print("Starting server. Listening on port 50051.")
server.add_insecure_port("127.0.0.1:50001")
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
logging.debug('GRPC stop')
server.stop(0)
# 当server服务退出才会调用这里,然后执行下面函数
def handle_sigterm(*_):
all_rpcs_done_event = server.stop(30)
all_rpcs_done_event.wait(30)
print("Shut down gracefully")
signal(SIGTERM, handle_sigterm)
signal(SIGINT, handle_sigterm)
server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig()
serve()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# 2.2.2 grpc-server/recommendations.py
# recommendations.py
from protos.recommendations.recommendations_pb2 import (
BookCategory,
BookRecommendations
)
books_by_category = {
BookCategory.MYSTERY: [
BookRecommendations(id=1, title="The Maltese Falcon"),
BookRecommendations(id=2, title="Murder on the Orient Express"),
BookRecommendations(id=3, title="The Hound of the Baskervilles"),
],
BookCategory.SCIENCE_FICTION: [
BookRecommendations(id=4, title="The Hitchhiker's Guide to the Galaxy"),
BookRecommendations(id=5, title="Ender's Game"),
BookRecommendations(id=6, title="The Dune Chronicles"),
],
BookCategory.SELF_HELP: [
BookRecommendations(id=7, title="The 7 Habits of Highly Effective People"),
BookRecommendations(id=8, title="How to Win Friends and Influence People"),
BookRecommendations(id=9, title="Man's Search for Meaning"),
],
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 2.3 grpc客户端
# 2.3.1 grpc-client/app.py
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from controllers.marketplace import app
if __name__ == "__main__":
app.run(debug=True)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 2.3.2 grpc-client/controllers/marketplace.py
import json
import os
import grpc
from flask import Flask, render_template, jsonify
from protos.recommendations.recommendations_pb2 import RecommendationsRequest, BookCategory
from protos.recommendations.recommendations_pb2_grpc import RecommendationsStub
from google.protobuf.json_format import MessageToJson
app = Flask(__name__)
recommendations_host = os.getenv("RECOMMENDATIONS_HOST", "localhost")
recommendations_channel = grpc.insecure_channel(
f"{recommendations_host}:50051"
)
recommendations_client = RecommendationsStub(recommendations_channel)
@app.route("/")
def home_page():
recommendations_request = RecommendationsRequest(
user_id=1, category=BookCategory.MYSTERY, max_results=3
)
recommendations_response = recommendations_client.Recommend(
recommendations_request
)
serialized = json.loads(MessageToJson(recommendations_response))
return jsonify(serialized)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
上次更新: 2024/3/13 15:35:10