-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecommendations_server.py
70 lines (60 loc) · 2.3 KB
/
recommendations_server.py
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
59
60
61
62
63
64
65
66
67
68
69
70
from concurrent import futures
import random
import grpc
from proto.recommendations_pb2 import (
BookCategory,
BookRecommendation,
RecommendationResponse,
)
import proto.recommendations_pb2_grpc as recommendations_pb2_grpc
# 這裡可以用其他的資料來源取代,只是為了方便,在此建立一個簡易的資料庫
# 資料庫物件
books_by_category = {
BookCategory.MYSTERY: [
BookRecommendation(id=1, title="The Maltese Falcon"),
BookRecommendation(id=2, title="Murder on the Orient Express"),
BookRecommendation(id=3, title="The Hound of the Baskervilles"),
],
BookCategory.SCIENCE_FICTION: [
BookRecommendation(
id=4, title="The Hitchhiker's Guide to the Galaxy"
),
BookRecommendation(id=5, title="Ender's Game"),
BookRecommendation(id=6, title="The Dune Chronicles"),
],
BookCategory.SELF_HELP: [
BookRecommendation(
id=7, title="The 7 Habits of Highly Effective People"
),
BookRecommendation(
id=8, title="How to Win Friends and Influence People"
),
BookRecommendation(id=9, title="Man's Search for Meaning"),
],
}
# 實作class function
# RecommendationService是自己取得名字
# 繼承 recommendations_pb2_grpc.RecommendationsServicer 此service
# 實作 Recommend這個方法
class RecommendationService(recommendations_pb2_grpc.RecommendationsServicer):
def Recommend(self, request, context):
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 RecommendationResponse(recommendations=books_to_recommend)
# 將剛剛實作完的service架起來
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
recommendations_pb2_grpc.add_RecommendationsServicer_to_server(
RecommendationService(), server
)
print('server start ')
server.add_insecure_port("[::]:50051")
server.start()
server.wait_for_termination()
if __name__ == "__main__":
serve() # run gRPC server