Skip to content

Instantly share code, notes, and snippets.

@josephlewis42
Created September 12, 2015 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephlewis42/ff78c368a91cd3110a78 to your computer and use it in GitHub Desktop.
Save josephlewis42/ff78c368a91cd3110a78 to your computer and use it in GitHub Desktop.
A simple python HTTP webserver that displays and reads a form
#!/usr/bin/python
import SimpleHTTPServer
import SocketServer
import logging
import cgi
import sys
# we choose where the server will listen, in this case http://localhost:8001
PORT = 8001
# the text of the homepage
WEBPAGE = """
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1>My Form</h1>
<form method="POST" action="/">
<input type="text" name="firstname">First Name</input>
<input type="checkbox" name="cookies">Do You Like Cookies?</input>
<input type="submit">
</form>
</body>
</html>
"""
# we create a server that has a base SimpleHTTPServer
class MyServer(SimpleHTTPServer.SimpleHTTPRequestHandler):
# a GET request is what you do when you fetch a page
def do_GET(self):
logging.warning("Serving Page")
self.send_response(200) # ok
self.send_header('Content-type', 'text/html') # we're sending HTML
self.end_headers()
self.wfile.write(WEBPAGE) # send over our homepage
# a POST is done when you upload files or submit forms
def do_POST(self):
logging.warning("Doing POST")
# we need to get the values of the submitted form out
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
self.send_response(200) # ok
self.send_header('Content-type', 'text/html') # we're sending HTML
self.end_headers()
self.wfile.write("""
<html>
<head>
<title>Your Results</title>
</head>
<body>
""")
# if the user submitted a "firstname" field in the form
if form.has_key("firstname"):
self.wfile.write("Your name is: " + form["firstname"].value)
# if the user checked the cookies box; if the box isn't checked
# the form won't even have the cookies key.
if form.has_key("cookies"):
self.wfile.write(" and you like cookies.")
else:
self.wfile.write(" and you hate cookies, you monster!")
self.wfile.write("""
</body>
</html>
""")
print "Serving at: http://{}:{}".format("localhost", PORT)
# setup the server
http = SocketServer.TCPServer(("", PORT), MyServer)
# keep looping looking for requests
http.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment