mnemo_cards/mnemo_cards/web_server.py
2025-11-11 02:55:41 +03:00

88 lines
No EOL
3.5 KiB
Python

# Directory to serve your website files
WEBSITE_DIRECTORY = "/Users/dmitry/StudioProjects/mnemo_cards/mnemo_cards/build/web"
import http.server
import socketserver
import os
import urllib.request
class ProxyHTTPRequestHandler(http.server.CGIHTTPRequestHandler):
def end_headers(self):
# Add CORS headers
self.send_header("Access-Control-Allow-Origin", "*") # Allow all origins
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") # Allowed methods
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization") # Allowed headers
super().end_headers()
def do_OPTIONS(self):
# Handle preflight requests
self.send_response(204) # No Content
self.end_headers()
def do_GET(self):
# Check if the request is for a local file
local_file_path = os.path.join(WEBSITE_DIRECTORY, self.path.lstrip("/"))
if 'version.json' in local_file_path:
local_file_path = local_file_path.split('?')[0]
if self.path == '/':
local_file_path = os.path.join(WEBSITE_DIRECTORY, 'index.html')
if os.path.isfile(local_file_path):
self.serve_local_file(local_file_path)
else:
# Otherwise, act as a proxy
self.handle_proxy_request()
def do_POST(self):
content_length = int(self.headers.get('Content-Length', 0))
post_data = self.rfile.read(content_length) # Read the POST body
# Extract target URL (Remove the leading '/')
target_url = 'http://localhost:8080/' + self.path[1:]
try:
# Forward the POST request
request = urllib.request.Request(target_url, data=post_data, method="POST")
for header in self.headers:
request.add_header(header, self.headers[header]) # Copy headers
with urllib.request.urlopen(request) as response:
content = response.read()
self.send_response(response.getcode())
self.send_header("Content-Type", response.headers.get("Content-Type", "text/html"))
self.end_headers()
self.wfile.write(content)
except Exception as e:
self.send_error(500, f"Error forwarding POST request: {e}")
def serve_local_file(self, local_file_path):
self.send_response(200)
self.send_header("Content-Type", self.guess_type(local_file_path))
self.end_headers()
with open(local_file_path, "rb") as file:
self.wfile.write(file.read())
def handle_proxy_request(self):
try:
# Remove the leading '/' to get the actual URL
target_url = 'http://localhost:8080/' + self.path[1:]
with urllib.request.urlopen(target_url) as response:
content = response.read()
self.send_response(response.getcode())
self.send_header("Content-Type", response.headers.get("Content-Type", "text/html"))
self.end_headers()
self.wfile.write(content)
except Exception as e:
self.send_error(500, f"Error fetching URL: {e}")
if __name__ == "__main__":
PORT = 8000
# Change the working directory to the website directory
os.chdir(WEBSITE_DIRECTORY)
# Start the server
with socketserver.TCPServer(("", PORT), ProxyHTTPRequestHandler) as httpd:
print(f"Serving on port {PORT}")
print(f"Serving website from: {os.path.abspath(WEBSITE_DIRECTORY)}")
httpd.serve_forever()