Created
January 31, 2014 19:33
-
-
Save maurostorch/8741318 to your computer and use it in GitHub Desktop.
Simple and light HTTP server in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
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.
Is this Python 2 or Python 3 ?
Python 3
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
@VAkris you say python3 but BaseHTTPServer isn't in python 3 and the print statements are python 2
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
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)"