Skip to content

Instantly share code, notes, and snippets.

@vgezer
Last active May 25, 2021 13:52
Show Gist options
  • Save vgezer/59c002587e655ff69b8f2f1f0c4ca7a4 to your computer and use it in GitHub Desktop.
Save vgezer/59c002587e655ff69b8f2f1f0c4ca7a4 to your computer and use it in GitHub Desktop.
Simple Python HTTP Server with handler for POST and GET, no additional libraries required
# Python HTTP Server!
This is very basic Python HTTP server with ability of handling GET and POST requests.
For Python 2.x.
For Python 3.x see here: https://gist.github.com/vgezer/59c002587e655ff69b8f2f1f0c4ca7a4
This one handles multiple requests by creating multiple threads, preventing e.g. unresponsive server until restart, caused by Chrome.
## Installation
No installation!
## Configuration
Port number can be changed editing `PORT_NUMBER` value.
## Execution
`python http.py`
Tested on Windows and Linux
## Examples
* http://localhost:8080 # Homepage
* http://localhost:8080/test?name=Hello # GET Example
* http://localhost:8080/config # POST Example, send a value with form named "name"
#!/usr/bin/python
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import urlparse
import cgi
PORT_NUMBER = 8080
#This class will handles any incoming request from
#the browser
class Handler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
if self.path=="/":
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("Hello World! <br />")
self.wfile.write("<a href='test?name=Hello'>See GET in action.</a> <br />")
self.wfile.write("<form action='/config' method='POST'>Type anything here and press enter to see POST in action: <input type='text' name='name' id='name' value='Hello'/></form>")
return
elif self.path.startswith("/test"):
form = urlparse.parse_qs(urlparse.urlparse(self.path).query)
#print "Test: " + str(form['test'])
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
if(form.get('name') != None):
self.wfile.write("Chosen name: %s <br />\n" % str(form['name'][0]))
self.wfile.write("Yes!")
return
else:
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("Your server is running!")
return
#Handler for the POST requests
def do_POST(self):
if self.path=="/config":
self.send_response(200)
self.send_header('Content-type', "text/html")
self.end_headers()
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
if(form != None):
self.wfile.write("Form value: " + form["name"].value)
else:
self.send_response(200)
self.send_header('Content-type', "text/html")
self.end_headers()
self.wfile.write("Send POST request to '/config' with form name 'name' to see the result!")
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
""" This class allows to handle requests in separated threads.
No further content needed, don't touch this. """
try:
if __name__ == '__main__':
server = ThreadedHTTPServer(('', PORT_NUMBER), Handler)
print('Started httpserver on port: %s' % PORT_NUMBER)
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down the web server')
server.socket.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment