Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a simple HTTP python server to handle broken pipe

I create a simple python http server and I want it to display only files from a directory I want to, thus changing always returning "Hello world!" and also how could I handle the broken pipe errors? I tried to do a try catch there but I'm not sure if it's working:

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

PORT_NUMBER = 8089

#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):

    #Handler for the GET requests
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        self.wfile.write("Hello World !")
        return

try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started http server on port ' , PORT_NUMBER

    #Wait forever for incoming http requests
    server.serve_forever()

except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    server.socket.close()
except socket.error:
    pass

This is my Error:

someIP - - [25/Dec/2019 09:17:11] "GET someFILE HTTP/1.0" 200 -
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 293, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/SocketServer.py", line 657, in __init__
    self.finish()
  File "/usr/lib/python2.7/SocketServer.py", line 716, in finish
    self.wfile.close()
  File "/usr/lib/python2.7/socket.py", line 283, in close
    self.flush()
  File "/usr/lib/python2.7/socket.py", line 307, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe

like image 758
J. Homer Avatar asked Jan 20 '26 09:01

J. Homer


1 Answers

Example which follows is the basic example of creating basic web server for serving the static files. Additional comments you can find inside the code, with one additional note: 403 Forbidden implementation can be replaced with file indexing page, for what you need to do the additional generation of it (according to your question, this is out of scope for now.)

from http.server import HTTPServer, BaseHTTPRequestHandler
from os import curdir, sep, path


class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200) #Request received, sending OK status
        self.end_headers()
        try:
            if(path.isdir(self.path)): #Checking if user requested access to directory (not to a particular file)
                self.send_response(403)
                self.wfile.write(str.encode("Listing of directories not permitted on this server")) #Preventing directory listing, in case you don't want to allow file indexing.
            else: #If user is requesting access to a file, file content is read and displayed.
                f = open(curdir + sep + self.path, 'rb')
                self.wfile.write(f.read())
                f.close()
        except IOError: #Covering the 404 error, in case user requested non-existing file
            print("File "+self.path+" not found")
            self.send_response(404)


httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
httpd.serve_forever()
like image 171
user5214530 Avatar answered Jan 22 '26 23:01

user5214530