Search code examples
pythonwebserverserversocket

why does my pyhhont webserver doesnt work?


i want to make a multithreaded python web server with logging i wrote this code and it has no error but it doesnt show the page and doesnt write anything in log file and i dont know which part is wrong

from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from os import curdir,sep
port_number=8080
class myhandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path=="/":
            self.path="/a1.html" 
        try:
             sendrep=False
             if self.path.endswith(".html"):
                 sendrep-True
                 mimetype='text/html'
             if self.path.endswith(".jpg"):
                 sendrep-True  
                 mimetype='image/jpg' 
             if self.path.endswith(".gif"):
                 sendrep-True 
                 mimetype='image/jpg'
             if self.path.endswith(".js"):
                 sendrep-True 
                 mimetype='application/javascript'
             if self.path.endswith(".css"):
                 sendrep-True 
                 mimetype='text/css'
             if sendrep==True:
                f=open(curdir+sep+self.path)
                self.send_response(200)
                self.send_header('content-type',mimetype)
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
             return
        except IOError:
            self.send_error(404,'file not found: %s' % self.path)
        log_file = open('logfile.txt', 'w')
        def log_message(self, format, *args):
            self.log_file.write("%s - - [%s] %s %s\n" %(self.client_address[0],self.log_date_time_string(),curdir+sep+self.path,format%args))
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
     """Handle requests in a separate thread."""
print("asb")
try:
     server=ThreadedHTTPServer(('127.0.0.1',8080),myhandler)
     server.serve_forever()
except KeyboardInterrupt:
if KeyboardInterrupt:
    print('shut down the server')
    server.socket.close()

Solution

  • Two things:

    1. there is sendrep-True in several lines which is not a syntax error, but a useless statement. It should be sendrep = True (equals not minus).

    2. You also open your file in binary mode: f=open(curdir+sep+self.path, "br") otherwise you will get a TypeError: a bytes-like object is required, not 'str'