-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
76 lines (59 loc) · 2.38 KB
/
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
71
72
73
74
75
76
import socket
from concurrent import futures
from uuid import uuid4
import grpc
import geoService_pb2
import geoService_pb2_grpc
from services.geo_service import GeoService
import etcd3
class GeoServiceServer(geoService_pb2_grpc.GeoServiceServicer):
def __init__(self):
self.geo_service = GeoService()
def GetAllCountries(self, request, context):
response = geoService_pb2.GetAllCountriesReply()
response.countries.extend(self.geo_service.get_countries())
return response
def GetCities(self, request, context):
response = geoService_pb2.GetCitiesReply()
response.cities.extend(self.geo_service.get_cities(request.name))
return response
def GetSubCountries(self, request, context):
response = geoService_pb2.GetSubCountriesReply()
response.subCountries.extend(self.geo_service.get_states(request.name))
return response
def GetLocationOfIp(self, request, context):
response = geoService_pb2.GetLocationOfIpReply()
aux = self.geo_service.get_location_from_ip(request.direction)
if 'country' in aux and 'state' in aux:
response.country = aux['country']
response.state = aux['state']
else:
response.error = aux
return response
try:
etcd = etcd3.client(host="etcd", port=2379)
etcd.put('/services/geoService/' + str(uuid4()), socket.gethostbyname(socket.gethostname()))
except Exception:
pass
# create a gRPC server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
# use the generated function `add_GeoServiceServicer_to_server`
# to add the defined class to the server
geoService_pb2_grpc.add_GeoServiceServicer_to_server(
GeoServiceServer(), server)
# listen on port 50051
print('Starting server. Listening on port 50051.')
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()
# The server start() method is non-blocking.
# A new thread will be instantiated to handle requests.
# The thread calling server.start() will often not have any other work to do in the meantime.
# In this case, you can call server.wait_for_termination() to cleanly block the calling thread until the server terminates.
# # since server.start() will not block,
# # a sleep-loop is added to keep alive
# try:
# while True:
# time.sleep(86400)
# except KeyboardInterrupt:
# server.stop(0)