CMS 3D CMS Logo

server.py
Go to the documentation of this file.
1 import os
2 from http.server import HTTPServer, BaseHTTPRequestHandler
3 import mimetypes
4 import argparse
5 
6 class Serv(BaseHTTPRequestHandler):
7  def do_GET(self):
8  # Default route to serve the index.html file
9  if self.path == '/':
10  self.path = '/index.html'
11  # Serve the uploaded JavaScript file if requested
12  if self.path == '/modules_data.json':
13  self.path = '/modules_data.json'
14 
15  try:
16  file_path = self.path[1:] # Remove leading '/' to get the file path
17 
18  # Read the requested file
19  with open(file_path, 'rb') as file:
20  file_to_open = file.read()
21 
22  # MIME type of the file
23  mime_type, _ = mimetypes.guess_type(file_path)
24 
25  # Send the HTTP response
26  self.send_response(200)
27  if mime_type:
28  self.send_header("Content-type", mime_type)
29  self.end_headers()
30 
31  # Write the file content to the response
32  self.wfile.write(file_to_open)
33 
34  except FileNotFoundError:
35  # Handle file not found error
36  self.send_response(404)
37  self.send_header("Content-type", "text/html")
38  self.end_headers()
39  self.wfile.write(bytes("File not found", 'utf-8'))
40 
41  except Exception as e:
42  # Handle any other internal server errors
43  self.send_response(500)
44  self.send_header("Content-type", "text/html")
45  self.end_headers()
46  self.wfile.write(bytes(f"Internal server error: {str(e)}", 'utf-8'))
47 
48 def run(server_class=HTTPServer, handler_class=Serv, port=65432):
49  # Configure and start the HTTP server
50  server_address = ('localhost', port)
51  httpd = server_class(server_address, handler_class)
52  print(f"Server started at http://localhost:{port}")
53  httpd.serve_forever()
54 
55 if __name__ == "__main__":
56  # Parse command-line arguments to set the server port
57  parser = argparse.ArgumentParser(description='Start a simple HTTP server.')
58  parser.add_argument('--port', type=int, default=65432, help='Port to serve on (default: 65432)')
59  args = parser.parse_args()
60 
61  # Start the server with the specified port
62  run(port=args.port)
63 
def run(server_class=HTTPServer, handler_class=Serv, port=65432)
Definition: server.py:48
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def do_GET(self)
Definition: server.py:7