2

here is an example for a simple server:

import http.server
import socketserver

PORT = 80

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

the server itself works and the port is open but it opens the directory the code is in while i need it to open an html file that is in that directory.

How can i make it open the html file i want instead of the directory?

2
  • What URL are you using in the browser? Commented Nov 27, 2019 at 13:57
  • 2
    do you have index.html in that directory? I just checked your code and if I dont have index.html, it will show the files of that directory. Commented Nov 27, 2019 at 13:57

1 Answer 1

6

You can extend SimpleHTTPServer.SimpleHTTPRequestHandler and override the do_GET method to replace self.path with your_file.html if / is requested.

import SimpleHTTPServer
import SocketServer

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path = '/your_file.html'
        return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

Handler = MyRequestHandler
server = SocketServer.TCPServer(('0.0.0.0', 8080), Handler)

server.serve_forever()

More: Documentation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.