Skip to content

Commit

Permalink
Conversion to Flask Server
Browse files Browse the repository at this point in the history
  • Loading branch information
ryansurf committed May 27, 2024
1 parent 0604490 commit 07027d5
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 87 deletions.
10 changes: 10 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"server": {
"port" : 8000,
"ip_address" : "localhost"
},
"frontend": {
"website" : "True",
"port": 9000
}
}
50 changes: 44 additions & 6 deletions src/backend/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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):
"""
Expand Down
130 changes: 52 additions & 78 deletions src/backend/server.py
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion src/frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,6 @@
</div>
</div>
</div>
<script src="script.js"></script>
<script type="module" src="script.js"></script>
</body>
</html>
27 changes: 25 additions & 2 deletions src/frontend/script.js
Original file line number Diff line number Diff line change
@@ -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
Expand Down

0 comments on commit 07027d5

Please sign in to comment.