Skip to content

Instantly share code, notes, and snippets.

@maurostorch
Created January 31, 2014 19:33
Show Gist options
  • Save maurostorch/8741318 to your computer and use it in GitHub Desktop.
Save maurostorch/8741318 to your computer and use it in GitHub Desktop.
Simple and light HTTP server in Python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from httplib import HTTPResponse
from os import curdir,sep
#Create a index.html aside the code
#Run: python server.py
#After run, try http://localhost:8080/
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/index.html'
try:
sendReply = False
if self.path.endswith(".html"):
mimeType = 'text/html'
sendReply = True
if sendReply == 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!')
def run():
print('http server is starting...')
#by default http server port is 80
server_address = ('127.0.0.1', 8080)
httpd = HTTPServer(server_address, RequestHandler)
try:
print 'http server is running...'
httpd.serve_forever()
except KeyboardInterrupt:
httpd.socket.close()
if __name__ == '__main__':
run()
@maurostorch
Copy link
Author

Hi Maurostorch, How to use a wildcard at ports or set a range of ports to listen on.

Here "server_address = ('127.0.0.1', 8080)"

each run() is a single server in a single port. You could call it multiple times with some small changes in this code and using threads.

@pligor
Copy link

pligor commented Jan 30, 2022

Is this Python 2 or Python 3 ?

@VAkris
Copy link

VAkris commented Jan 30, 2022

Python 3

@pligor
Copy link

pligor commented Jan 30, 2022

Not currently working out of the box. For sure the print statement needs parenthesis by the way but even after fixing it, is not working. Tested on 3.9.9

@partylikeits1983
Copy link

@VAkris you say python3 but BaseHTTPServer isn't in python 3 and the print statements are python 2

@davidawcloudsecurity
Copy link

I don't have the index.html. I tot it is supppose to come up with a directory of where the file exist?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment