From 07027d5561c792640cb2644511797c3d315d1db0 Mon Sep 17 00:00:00 2001 From: ryansurf Date: Mon, 27 May 2024 02:54:33 -0700 Subject: [PATCH] Conversion to Flask Server --- config.json | 10 ++++ src/backend/helper.py | 50 ++++++++++++++-- src/backend/server.py | 130 ++++++++++++++++------------------------ src/frontend/index.html | 2 +- src/frontend/script.js | 27 ++++++++- 5 files changed, 132 insertions(+), 87 deletions(-) create mode 100644 config.json diff --git a/config.json b/config.json new file mode 100644 index 0000000..3872ca0 --- /dev/null +++ b/config.json @@ -0,0 +1,10 @@ +{ + "server": { + "port" : 8000, + "ip_address" : "localhost" + }, + "frontend": { + "website" : "True", + "port": 9000 + } +} \ No newline at end of file diff --git a/src/backend/helper.py b/src/backend/helper.py index d2d9739..9769f40 100644 --- a/src/backend/helper.py +++ b/src/backend/helper.py @@ -5,7 +5,14 @@ import json import api import art +import os import pandas as pd +from http.server import SimpleHTTPRequestHandler, HTTPServer + +with open('../../config.json') as f: + json_config = json.load(f) + +website_port = int(json_config["frontend"]["port"]) def arguments_dictionary(lat, long, city, args): """ @@ -167,12 +174,43 @@ def set_output_values(args, ocean): ocean["json_output"] = 1 return ocean -def start_website(website): - """ - If the WEBSITE .env variable is true, the webserver is started - """ - if website == True: - subprocess.Popen(["python", "-m", "http.server", "9000"], cwd="../frontend") +# def start_website(website): +# """ +# If the WEBSITE .env variable is true, the webserver is started +# """ +# if website == True: +# subprocess.Popen(["python", "-m", "http.server", str(website_port)], cwd="../frontend") + +# def start_website(website, config_file_path="../../config.json"): +# """ +# If the WEBSITE json variable is true, the web server is started +# """ +# if website: +# try: +# # Set the directory where the files to be served are located +# os.chdir("../frontend") + +# # Custom handler to serve config.json +# class CustomHandler(SimpleHTTPRequestHandler): +# def do_GET(self): +# if self.path == '/config.json': +# with open(config_file_path, 'rb') as f: +# self.send_response(200) +# self.send_header('Content-type', 'application/json') +# self.end_headers() +# self.wfile.write(f.read()) +# else: +# super().do_GET() + +# # Create a custom HTTP server +# httpd = HTTPServer(("", website_port), CustomHandler) +# print(f"Website started on port {website_port}...") + +# # Serve files indefinitely +# httpd.serve_forever() +# except Exception as e: +# print("Error starting the server:", e) + def json_output(data_dict): """ diff --git a/src/backend/server.py b/src/backend/server.py index 1523971..c6d92d2 100644 --- a/src/backend/server.py +++ b/src/backend/server.py @@ -1,89 +1,63 @@ -""" -HTTP Server Module -""" - -import os -import http.server +from flask import Flask, send_file, send_from_directory, request import subprocess +import json import helper -from urllib.parse import urlparse, parse_qs -from dotenv import load_dotenv -from helper import query_to_args_list - -# Load environment variables from .env file -load_dotenv(override=True) -port_env = int(os.getenv("PORT")) -website = bool(os.getenv("WEBSITE")) +import sys +import asyncio +import urllib.parse -#Starts website if website==True -helper.start_website(website) +app = Flask(__name__) +with open('../../config.json') as f: + json_config = json.load(f) -class MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler): - """ - Handles HTTP requests - """ +port_json = int(json_config["server"]["port"]) +website = bool(json_config["frontend"]["website"]) - # pylint: disable=C0103 - def do_GET(self): - """ - Function for GET requests - """ - # Parse the query parameters - parsed_url = urlparse(self.path) +@app.route('/config.json') +def serve_config(): + return send_from_directory('../../', 'config.json') - # Extract the arguments from the query parameters - args = query_to_args_list(parsed_url.query) - - if "help" in args: - # If 'help' is in the args, read and return the content of help.txt - try: - with open( - "../../help.txt", "r", encoding="utf-8", errors="ignore" - ) as file: - help_text = file.read() - self.send_response(200) - self.send_header("Content-type", "text/plain") - self.send_header( - "Access-Control-Allow-Origin", "*" - ) # Allow requests from any origin - self.end_headers() - self.wfile.write(help_text.encode()) - except FileNotFoundError: - self.send_response(404) - self.send_header("Content-type", "text/plain") - self.end_headers() - self.wfile.write(b"help.txt not found") - else: +@app.route('/help') +def serve_help(): + return send_from_directory('../../', 'help.txt') - # Otherwise, run the main.py script with the provided arguments - result = subprocess.run( - ["python3", "main.py"] + args, - capture_output=True, - text=True, - check=True, - ) - self.send_response(200) - self.send_header("Content-type", "text/plain") - self.send_header( - "Access-Control-Allow-Origin", "*" - ) # Allow requests from any origin - self.end_headers() - self.wfile.write(result.stdout.encode()) +@app.route('/home') +def serve_index(): + return send_file('../frontend/index.html') +@app.route('/script.js') +def serve_script(): + return send_file('../frontend/script.js') -def run( - server_class=http.server.HTTPServer, handler_class=MyHTTPRequestHandler, port=8000 -): - """ - Run the server! - """ - server_address = ("", port_env) - httpd = server_class(server_address, handler_class) - print(f"Server running on port {port}") +@app.route('/') +def default_route(): + query_parameters = urllib.parse.parse_qsl(request.query_string.decode(), keep_blank_values=True) + parsed_parameters = [] - httpd.serve_forever() - - -if __name__ == "__main__": - run(port=port_env) + for key, value in query_parameters: + if value: + parsed_parameters.append(f"{key}={value}") + else: + parsed_parameters.append(key) + + # Join the parsed parameters list into a single string + args = ','.join(parsed_parameters) + + async def run_subprocess(): + result = subprocess.run( + ["python3", "main.py", args], + capture_output=True, + text=True, + check=True, + ) + return result.stdout + + # Run subprocess asynchronously + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + result = loop.run_until_complete(run_subprocess()) + return result + +if __name__ == '__main__': + app.run(port=port_json) \ No newline at end of file diff --git a/src/frontend/index.html b/src/frontend/index.html index ccf67bb..5e7c820 100644 --- a/src/frontend/index.html +++ b/src/frontend/index.html @@ -75,6 +75,6 @@ - + \ No newline at end of file diff --git a/src/frontend/script.js b/src/frontend/script.js index 637a201..94ffaf6 100644 --- a/src/frontend/script.js +++ b/src/frontend/script.js @@ -1,6 +1,29 @@ // ipAddress = the ip of the machine that is hosting the server -const ipAddress = 'localhost'; -const port = 8000; + +let port; +let ipAddress; + +fetch('/config.json', { + method: 'GET', + mode: 'no-cors', // Add the 'no-cors' mode + }) +.then(response => { + if (!response.ok) { + throw new Error(`HTTP error! Status: ${response.status}`); + } + return response.json(); +}) +.then(config => { + // Pass the config to another function if needed + useConfig(config); +}) +.catch(error => console.error('Error loading config:', error)); + +function useConfig(config) { + port = config["server"]["port"]; + ipAddress = config["server"]["ip_address"]; +} + document.getElementById("reportForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent default form submission