0

I am trying' to make a website using python HTTPServer, I know I could use any frameworks like flask or Django, but I don't want to.

The python code is:

from http import server
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

# importing all the modules 

with open('settings.json', 'r') as json_file:
    setting = json.load(json_file)
    port = setting['port']
    start_at = setting['start_at']

# loading settings 

class Serv(BaseHTTPRequestHandler):

    def do_GET(self):
        
        try:
            file_to_open = open(start_at).read()
            self.send_response(200)
        except:
            file_to_open = "File not found"
            self.send_response(404)
        self.end_headers()
        self.wfile.write(bytes(file_to_open, 'utf-8'))

def start_server():
    """
    Starts the server
    """
    try:
        server = HTTPServer(('', port), Serv)
        print(f"[SERVER] Starting the server at port {port}")
        server.serve_forever()
    except KeyboardInterrupt:
        print(f"[CLOSING] Closing the editor, see you again next time...")

if __name__ == "__main__":
    start_server()

And when I try to serve it, the index.html file works perfectly but the icon and js files are not working. I know I could use the python -m http.server but I don't prefer to.

I will give some screenshots The image

The app.js is displaying the same code in HTML but actually, I didn't write anything to the javascript file

deceze
  • 510,633
  • 85
  • 743
  • 889
  • It's because you are reading the same file each time, i.e., `file_to_open = open(start_at).read()`. You should get the requested file from the request and read that file. –  Dec 15 '20 at 15:58
  • Your server isn't even trying to serve any file other than `setting['start_at']`…?! – deceze Dec 15 '20 at 15:58
  • Hint: `path = self.translate_path(self.path)` –  Dec 15 '20 at 16:04

1 Answers1

0

This might help with your answer: Serve directory in Python 3

As others have said looks like you're opening the same file. To server other files, you need to parse self.path and open based on that.

KKS
  • 458
  • 5
  • 10