1
+ # This script creates a gRPC server that serves train station data by reading data from a sqlite3 database
1
2
import grpc
2
3
from concurrent import futures
3
4
import sqlite3
4
5
5
6
import stations_pb2 as stations_pb2
6
7
import stations_pb2_grpc as stations_pb2_grpc
7
8
8
- class StationsServicer (stations_pb2_grpc .StationsServicer ):
9
-
9
+ # Connect to the SQLite3 database
10
+ def connectDB ():
11
+ connection = sqlite3 .connect ('data/DataAnalyzer.db' )
12
+ return connection
10
13
14
+ # StationsServicer class is implemented to handle the gRPC requests
15
+ class StationsServicer (stations_pb2_grpc .StationsServicer ):
16
+ # Read function is implemented to read the data from the sqlite3 database based on the zipcode passed in the request
11
17
def Read (self , readRequestPB , context ):
12
-
18
+ connectDB ()
19
+
13
20
cp = readRequestPB .zipcode
14
- connection = sqlite3 .connect ('data/DataAnalyzer.db' )
15
21
cur = connection .cursor ()
22
+
23
+ # sql query to fetch the data based on the zipcode
16
24
sql = "SELECT gare_alias_libelle, gare_regionsncf, adresse_cp, departement, uic_code FROM referentiel WHERE adresse_cp = " + cp
17
-
18
25
exe = cur .execute (sql )
19
-
20
26
rslt = exe .fetchall ()
21
- print ( rslt )
22
-
27
+
28
+ # list to hold the data to be returned as the response
23
29
result = []
24
30
25
31
for i in rslt :
26
32
response = stations_pb2 .readResponsePB ().Value ()
27
33
response .uic_code = str (i [4 ])
28
34
response .gare_alias_libelle = str (i [0 ])
29
- response .gare_alias_libelle = str (i [3 ])
30
35
response .adresse_cp = str (i [2 ])
31
36
response .gare_regionsncf = str (i [1 ])
32
37
result .append (response )
@@ -36,7 +41,8 @@ def Read(self, readRequestPB, context):
36
41
print (response_list )
37
42
38
43
return response_list
39
-
44
+
45
+ # serve function starts the gRPC server and listens on port 9600
40
46
def serve ():
41
47
42
48
server = grpc .server (futures .ThreadPoolExecutor (max_workers = 10 ))
0 commit comments