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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.