Skip to content
Snippets Groups Projects
Commit cec134a9 authored by Sara Savanovic Djordjevic's avatar Sara Savanovic Djordjevic
Browse files

add: working sqlite db with example data

parent 8dc41c17
No related branches found
No related tags found
No related merge requests found
No preview for this file type
from flask import Flask
from http.server import HTTPServer, BaseHTTPRequestHandler
from consts import DB_NAME, COLLECTION, MONGO_URI, MONGO_CERT_PATH, SSL_CERT_PATH, SSL_KEY_PATH, HOST, PORT
from consts import DB_NAME, COLLECTION, SSL_CERT_PATH, SSL_KEY_PATH, HOST, PORT
from map.get_markers import get_all_markers
from pymongo import MongoClient
from pymongo.server_api import ServerApi
import ssl
import keyboard
import sqlite3
app = Flask(__name__)
terminate_server = 0
# Initialise MongoDB connection
# Initialise SQLite database connection
def init_database():
try:
client = MongoClient(MONGO_URI,
tls=True,
tlsCertificateKeyFile=MONGO_CERT_PATH,
server_api=ServerApi('1'))
db = client[DB_NAME]
collection = db[COLLECTION]
print("Connected to MongoDB")
return client
except Exception as e:
print(f"Failed to connect to MongoDB: {e}")
#try:
# Connect to the SQLite database
conn = sqlite3.connect('server/sql_db/icedb')
# Return the connection object
return conn
#except Exception as e:
# print(f"Failed to connect to SQLite database: {e}")
# return None
class IceHTTPServer(HTTPServer):
def __init__(self, server_address, handler_class, client):
def __init__(self, server_address, handler_class, cursor):
super().__init__(server_address, handler_class)
self.client = client
self.cursor = cursor
def get_request(self):
request, client_address = super().get_request()
......@@ -40,13 +36,10 @@ class IceHTTPServer(HTTPServer):
# Define custom HTTP class
class IceHTTP(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
self.client = server.client
self.cursor = server.cursor # Accessing cursor from server
super().__init__(request, client_address, server)
def do_GET(self):
db = self.client[DB_NAME]
col = db[COLLECTION] # Set collection pointer
# Root path
if self.path == '/':
self.send_response(200)
......@@ -56,14 +49,16 @@ class IceHTTP(BaseHTTPRequestHandler):
self.wfile.write(b"Root path hit!")
# Update_map endpoint
elif self.path == '/update_map': # NB: should be POST?
get_all_markers(self, col)
elif self.path == '/update_map': # NB: should be POST?
get_all_markers(self, self.cursor) # Accessing cursor from self
# Listen for pressing of q key to terminate server
def on_key_press(server, event):
def on_key_press(server, event, cursor, conn):
if event.name == 'q':
print('Terminating server...')
server.server_close()
cursor.close()
conn.close()
keyboard.unhook_all()
quit()
......@@ -71,7 +66,8 @@ def on_key_press(server, event):
# Start a server on port 8443 using self defined HTTP class
if __name__ == "__main__":
# Initialise database connection
client = init_database()
conn = init_database()
cursor = conn.cursor()
try:
# Load SSL certificate and private key
......@@ -79,13 +75,15 @@ if __name__ == "__main__":
ssl_context.load_cert_chain(SSL_CERT_PATH, SSL_KEY_PATH)
# Create HTTP server with SSL support
server = IceHTTPServer((HOST, PORT), IceHTTP, client)
server = IceHTTPServer((HOST, PORT), IceHTTP, cursor)
server.socket = ssl_context.wrap_socket(server.socket, server_side=True)
print("Server running on port ", PORT)
# Register key press event handler
keyboard.on_press(lambda event: on_key_press(server, event))
keyboard.on_press(lambda event: on_key_press(server, event, cursor, conn))
print("Server running on port ", PORT)
# Run server indefinitely
server.serve_forever()
......
No preview for this file type
......@@ -4,25 +4,43 @@ from bson import json_util
current_dir = os.path.dirname(__file__)
parent_dir = os.path.abspath(os.path.join(current_dir, '..'))
sys.path.append(parent_dir)
import json
# get_markers requests all marker data from mongoDB
def get_all_markers(self, col):
def get_all_markers(self, cursor):
try:
# Fetch marker data from DB
marker_cursor = col.find({})
marker_data = list(marker_cursor)
# Remove ObjectId field documents to allow for easy JSON to BSON conversion
for document in marker_data:
document.pop('_id', None)
if marker_data: # Data found in DB, convert from BSON to JSON
resp_code = 200
marker_json_list = [json_util.dumps(document) for document in marker_data]
marker_json = "[" + ",".join(marker_json_list) + "]"
else: # Data not found in DB
resp_code = 404
marker_json = '[]'
# Fetch all data
cursor.execute('''
SELECT m.MeasurementID, m.SensorID, m.TimeMeasured, m.Latitude, m.Longitude,
m.MeasuredThickness, m.Accuracy, s.SensorType, s.Active
FROM Measurement m
INNER JOIN Sensor s ON m.SensorID = s.SensorID
''')
rows = cursor.fetchall()
data = []
for row in rows:
measurement = {
'MeasurementID': row[0],
'TimeMeasured': row[1],
'Latitude': row[2],
'Longitude': row[3],
'MeasuredThickness': row[4],
'Accuracy': row[5],
'Sensor': {
'SensorID': row[6],
'SensorType': row[7],
'Active': bool(row[8])
}
}
data.append(measurement)
resp_code = 200
# Convert the list of dictionaries to JSON
marker_json = json.dumps(data, indent=4)
except Exception as e:
print(f"An error occurred while querying MongoDB: {e}")
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment