Commit fcb6de27 authored by Thomas Stone's avatar Thomas Stone
Browse files

Fixed Flask Backend/cleaned up frontend

parent aedc1c80
'''
Revised from the code segments:
http://stackoverflow.com/questions/23264569/python-3-x-basehttpserver-or-http-server
and
https://wiki.python.org/moin/BaseHttpServer#Official_Documentation
Xiannong Meng
2015-09-12
'''
from http.server import BaseHTTPRequestHandler, HTTPServer
import urllib
import time
import os
HOST_NAME = "localhost"
#HOST_NAME = "brki164-lnx-20" # any real host name where the server is running
HOST_PORT = 9000
server_name = "Python Server"
class MyServer(BaseHTTPRequestHandler):
"""
def __init__(self, server_name, port=HOST_PORT):
self.server_name = sever_name
self.port = port
"""
def do_HEAD(self):
print("in do_HEAD");
okay = self.check_file(self.path)
if okay == True:
self.send_response(200) # good file
else:
self.send_response(404) # bad file, we lump all codes for now
cont_type = self.check_type(self.path)
self.send_header("Server", server_name)
self.send_header("Content-Type", cont_type)
self.end_headers()
def do_GET(self):
print("in do_GET");
if (self.path == "/"): # send form
self.send_response(200)
length = self.find_file_length("/index.html")
self.send_header("Server", server_name)
self.send_header("Content-Length", length)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.send_file("/index.html")
return
okay = self.check_file(self.path)
if okay == True:
self.send_response(200) # good file
cont_type = self.check_type(self.path)
length = self.find_file_length(self.path)
self.send_header("Server", server_name)
self.send_header("Content-Length", length)
self.send_header("Content-Type", cont_type)
self.end_headers()
self.send_file(self.path)
else:
self.send_response(404) # bad file
self.send_header("Server", server_name)
bad_request = "<html><body><h3>404: page not found</h3></body></html>"
length = len(bad_request)
self.send_header("Content-Length", length)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(bytes(bad_request.encode("utf8")))
# self.send_response(404) # bad file, we lump all codes for now
def do_POST(self):
length = int(self.headers['Content-Length'])
post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
# You now have a dictionary of the post data
print("post data: ", post_data)
ret_data = self.build_data(post_data)
length = len(ret_data)
self.send_response(200) # good request
self.send_header("Server", server_name)
self.send_header("Content-Length", length)
self.send_header("Content-Type", "text/html")
self.end_headers()
# now you have a dictionary of post data
self.wfile.write(bytes(ret_data.encode("utf-8")))
# self.wfile.write(bytes("Lorem Ipsum".encode("utf-8")))
def build_data(self, post_data):
"""
The post_data is in the form of
{'key1': ['val1'], 'key2': ['val2'], 'key3': ['val3']}
e.g.,
{'SecondInput': ['zx z'], 'FirstInput': ['124'], 'Submit': ['Submit']}
"""
ret_str = ""
for k in post_data:
ret_str = ret_str + "key : " + str(k) + "\ndata : " + str(post_data[k]) + "\n"
ret_str = ret_str + "\n"
return ret_str
def find_file_length(self, path):
first = path.find("/")
if first != 0:
return 0
# now we know the '/' leads the path, remove it
path = path[1:]
length = os.path.getsize(path)
return length
def check_file(self, path):
"""
Check to see if file or path exists.
(for now, we only deal with files, need to handle directories
"""
first = path.find("/")
if first != 0:
return False # when we handle directory, this needs change
# now we know the '/' leads the path, remove it
path = path[1:]
okay = False
try:
# r = open(path, encoding = "utf-8")
okay = os.path.exists(path)
except OSError:
pass
return okay
def send_file(self, path):
f = None
data = None
path = path[1:]
try:
# f = open(path, encoding = "utf-8")
f = open(path, "rb")
data = f.read()
f.close()
# self.wfile.write(bytes(data, "utf-8"))
self.wfile.write(bytes(data))
except OSError:
pass
def check_type(self, path):
file_type = "text/html" # default
if path.endswith(".jpg") or \
path.endswith(".jpeg"):
file_type = "image/jpeg" # jpeg image
elif path.endswith(".png"):
file_type = "image/png" # png image
elif path.endswith(".js"):
file_type = "text/javascript" # javascript
return file_type
if __name__ == '__main__':
httpd = HTTPServer((HOST_NAME, HOST_PORT), MyServer)
print(time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, HOST_PORT))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print(time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, HOST_PORT))
'''
myServer = HTTPServer((hostName, hostPort), MyServer)
print(time.asctime(), "Server Starts - %s:%s" % (hostName, hostPort))
try:
myServer.serve_forever()
except KeyboardInterrupt:
pass
myServer.server_close()
print(time.asctime(), "Server Stops - %s:%s" % (hostName, hostPort))
'''
import http.client
import sys
if __name__ == "__main__":
print("param: ", sys.argv[1], sys.argv[2])
conn = http.client.HTTPConnection(sys.argv[1], sys.argv[2])
conn.request("GET", "/index.html")
r = conn.getresponse()
print(r.status, r.reason)
'''
Created based on the information from:
https://docs.python.org/3/library/http.client.html
Xiannong Meng
2015-09-12
'''
import http.client
import sys
class MyHttpClient():
def __init__(self, s, p = 80):
"""
Creates the client object with server url 's'.
Parameters:
s: host name in the form of www.abc.com
p: port number, default is 80
Pre: s is a valid www host name
Post: a connection is established so the client
can retrieve information from the server.
If the response code is not 200 (OK), the
client simply quits.
"""
# print("host : port : ", s, p)
self.conn = http.client.HTTPConnection(s, p)
def request_HEAD(self):
"""
Request header information.
Pre: a connection has been established with the server.
Post: the header information is retrieved.
"""
self.conn.request("HEAD", "/")
self.res = None
try:
self.res = self.conn.getresponse()
if (self.res.status != 200):
print("Response code error.");
sys.exit(1)
else:
data = self.res.read()
print(data)
except http.client.ResponseNotReady:
print("sorry, server is not ready.")
except http.client.BadStatusLine:
print("sorry, bad status line.")
def request_page(self, page):
"""
Request a particular web page
Pre: a connection has been established with the server.
Post: the specified page is retrieved.
Parameters:
page: the web page to be retrieved
"""
self.conn.request("GET", page)
self.res = None
try:
self.res = self.conn.getresponse()
if (self.res.status != 200):
print("Response code error.");
sys.exit(1)
else:
data = self.res.read()
# print(self.res.msg)
self.data_type = self.parse_header(self.res.msg)
if self.data_type.cat == "text":
print(data)
elif self.data_type.cat == "image":
wf_name = "outf." + self.data_type.type
f = open(wf_name, "wb")
f.write(data);
f.close
except http.client.ResponseNotReady:
print("sorry, server is not ready.")
except http.client.BadStatusLine:
print("sorry, bad status line.")
def parse_header(self, msg):
"""
Parse the information from HTTP header
(at this moment, only the category and type are extracted)
Parameters:
msg: the HTTP header
Return: an object with two fields, 'cat' and 'type'
"""
c_type = self.res.getheader("Content-type")
content = type('typeclass', (object,),
{'cat':'', 'type':''})()
content.cat = "text" # default!
content.type = "html"
if c_type.find("image") != -1:
content.cat = "image"
if c_type.find("jpeg") != -1:
content.type = "jpeg"
elif c_type.find("png") != -1:
content.type = "png"
return content
def print_info(self):
"""
Print informatoin about this object
"""
print("Hi I am here.")
if __name__ == "__main__":
"""
sys.argv[1]: host in the form of "www.host.com"
sys.argv[2]: port, default 80
sys.argv[3]: web page, in the form of "/index.html"
"""
if len(sys.argv) != 4:
print("usage: python httpclient.py host port path")
sys.exit(1)
client = MyHttpClient(sys.argv[1], sys.argv[2])
# client.print_info()
# client.request_HEAD()
client.request_page(sys.argv[3])
import http.client
import sys
if __name__ == "__main__":
"""
Default https port is 443
"""
print("param: ", sys.argv[1], sys.argv[2])
conn = http.client.HTTPSConnection(sys.argv[1])
conn.request("GET", sys.argv[2])
r = conn.getresponse()
print(r.status, r.reason)
data = r.read()
print(data)
'''
Created based on the information from:
https://docs.python.org/3/library/http.client.html
and
http://stackoverflow.com/questions/2146383/https-connection-python
Xiannong Meng
2015-09-25
'''
import http.client
import sys
class MyHttpSClient():
def __init__(self, s, p = 80):
"""
Creates the client object with server url 's'.
Parameters:
s: host name in the form of www.abc.com
p: port number, default is 80
Pre: s is a valid www host name
Post: a connection is established so the client
can retrieve information from the server.
If the response code is not 200 (OK), the
client simply quits.
"""
# print("host : port : ", s, p)
self.conn = http.client.HTTPSConnection(s, p)
def request_HEAD(self):
"""
Request header information.
Pre: a connection has been established with the server.
Post: the header information is retrieved.
"""
self.conn.request("HEAD", "/")
self.res = None
try:
self.res = self.conn.getresponse()
if (self.res.status != 200):
print("Response code error.");
sys.exit(1)
else:
data = self.res.read()
print(data)
except http.client.ResponseNotReady:
print("sorry, server is not ready.")
except http.client.BadStatusLine:
print("sorry, bad status line.")
def request_page(self, page):
"""
Request a particular web page
Pre: a connection has been established with the server.
Post: the specified page is retrieved.
Parameters:
page: the web page to be retrieved
"""
self.conn.request("GET", page)
self.res = None
try:
self.res = self.conn.getresponse()
if (self.res.status != 200):
print("Response code error.");
sys.exit(1)
else:
data = self.res.read()
# print(self.res.msg)
self.data_type = self.parse_header(self.res.msg)
if self.data_type.cat == "text":
print(data)
elif self.data_type.cat == "image":
wf_name = "outf." + self.data_type.type
f = open(wf_name, "wb")
f.write(data);
f.close
except http.client.ResponseNotReady:
print("sorry, server is not ready.")
except http.client.BadStatusLine:
print("sorry, bad status line.")
def parse_header(self, msg):
"""
Parse the information from HTTP header
(at this moment, only the category and type are extracted)
Parameters:
msg: the HTTP header
Return: an object with two fields, 'cat' and 'type'
"""
c_type = self.res.getheader("Content-type")
content = type('typeclass', (object,),
{'cat':'', 'type':''})()
content.cat = "text" # default!
content.type = "html"
if c_type.find("image") != -1:
content.cat = "image"
if c_type.find("jpeg") != -1:
content.type = "jpeg"
elif c_type.find("png") != -1:
content.type = "png"
return content
def print_info(self):
"""
Print informatoin about this object
"""
print("Hi I am here.")
if __name__ == "__main__":
"""
sys.argv[1]: host in the form of "www.host.com"
sys.argv[2]: port, default 80
sys.argv[3]: web page, in the form of "/index.html"
"""
if len(sys.argv) != 4:
print("usage: python httpclient.py host port path")
sys.exit(1)
client = MyHttpSClient(sys.argv[1], sys.argv[2])
# client.print_info()
# client.request_HEAD()
client.request_page(sys.argv[3])
<html>
<title>HTML Page</title>
</head>
<body>
Hello World!<br>
<!--
<form method= "POST" action="/cgi-bin/cgiwrap/xmeng/cs363/cgi-process">
-->
<form method= "POST" action="/form">
<input type="text" name="FirstInput" size = "20">
<font color="red">
Type input into the box</font><br>
<br>
<input type="text" name="SecondInput" size = "20">
<font color="green">
Type input into the box</font><br>
<br>
<font color = "yellow"> <input type="submit" name="Submit" value = "Submit">
</font><br>
<br>
</form>
<br>
<br>
<h3>More free but formatted text</h3><br>
<p>We are here.</p>
</body></html>
'''
Revised from the code segments:
http://stackoverflow.com/questions/23264569/python-3-x-basehttpserver-or-http-server
and
https://wiki.python.org/moin/BaseHttpServer#Official_Documentation
Xiannong Meng
2015-09-12
'''
from http.server import BaseHTTPRequestHandler, HTTPServer
import urllib
import time
import os
#HOST_NAME = "localhost"
HOST_NAME = "brki164-lnx-20" # any real host name where the server is running
HOST_PORT = 9000
server_name = "Python Server"
class MyServer(BaseHTTPRequestHandler):
"""
def __init__(self, server_name, port=HOST_PORT):
self.server_name = sever_name
self.port = port
"""
def do_HEAD(self):
print("in do_HEAD");
okay = self.check_file(self.path)
if okay == True:
self.send_response(200) # good file
else:
self.send_response(404) # bad file, we lump all codes for now
cont_type = self.check_type(self.path)
self.send_header("Server", server_name)
self.send_header("Content-Type", cont_type)
self.end_headers()
def do_GET(self):
print("in do_GET");
if (self.path == "/search"): # send form
self.send_response(200)
length = self.find_file_length("/form.html")
self.send_header("Server", server_name)
self.send_header("Content-Length", length)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.send_file("/form.html")
return
okay = self.check_file(self.path)
if okay == True:
self.send_response(200) # good file
else:
self.send_response(404) # bad file, we lump all codes for now
if okay == True:
cont_type = self.check_type(self.path)
length = self.find_file_length(self.path)
self.send_header("Server", server_name)
self.send_header("Content-Length", length)
self.send_header("Content-Type", cont_type)
self.end_headers()
if okay == True: # actually sending the file
self.send_file(self.path)
else: # sending a default file
self.wfile.write(bytes("<html><head><title>Invalid file.</title></head>", "utf-8"))
self.wfile.write(bytes("<body><p>You requested an invalid file.</p>", "utf-8"))
self.wfile.write(bytes("<p>You accessed path: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
def do_POST(self):
length = int(self.headers['Content-Length'])
post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
# You now have a dictionary of the post data
print("post data: ", post_data)
# now you have a dictionary of post data
ret_data = self.build_data(post_data)
self.wfile.write(ret_data.encode("utf-8"))
self.wfile.write("Lorem Ipsum".encode("utf-8"))
def build_data(self, post_data):
"""
The post_data is in the form of
{'key1': ['val1'], 'key2': ['val2'], 'key3': ['val3']}
e.g.,
{'SecondInput': ['zx z'], 'FirstInput': ['124'], 'Submit': ['Submit']}
"""
ret_str = ""
for k in post_data:
ret_str = ret_str + "key : " + str(k) + "\ndata : " + str(post_data[k]) + "\n"
ret_str = ret_str + "\n"