Skip to content

Instantly share code, notes, and snippets.

@robinchew robinchew/server_old.py
Last active May 30, 2016

Embed
What would you like to do?
import SimpleHTTPServer
import SocketServer
from textwrap import dedent
from urlparse import urlparse, parse_qs
from collections import defaultdict
import csv
import os
import sys
from socket import SOL_SOCKET, SO_REUSEADDR
PORT = int(sys.argv[1])
CSV_PATH = 'fields.csv'
FIELDS = ('Degree', 'xyz')
def index(data):
posted_fields = []
for field in FIELDS:
for key, value in data.items():
if field == key:
posted_fields.append(True)
if len(posted_fields) == len(FIELDS):
csv_exists = os.path.isfile(CSV_PATH)
f = open(CSV_PATH, 'a')
if not csv_exists:
f.write(','.join(FIELDS)+'\n')
f.write(','.join(data[field] for field in FIELDS)+'\n')
f.close()
return '''
<h1>Index</h1>
<pre>{0}</pre>
<form method="POST">
{1}
<input type="submit" />
</form>
'''.format(
str(data),
''.join(
'{0} <input name="{0}" />'.format(name)
for name in FIELDS
)
)
def stat(data):
with open(CSV_PATH) as f:
reader = csv.DictReader(f)
count_map = {}
for row in reader:
if row[FIELDS[0]] in count_map:
count_map[row[FIELDS[0]]] = count_map[row[FIELDS[0]]] + 1
else:
count_map[row[FIELDS[0]]] = 1
return '''
<h1>Stat</h1>
<h2>{0}</h2>
<style>
table{{
border-collapse: collapse;
}}
td{{
border: 1px solid grey;
}}
</style>
<table>
<tr>
{1}
</tr>
</table>
'''.format(
FIELDS[0],
'</tr><tr>'.join(
'<td>{0}</td><td>{1}</td>'.format(value, count)
for value, count in count_map.items()
)
)
def create_handler(router):
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do(self, qs):
data = {}
for k, l in parse_qs(qs).items():
if len(l):
data[k] = l[0]
else:
data[k] = None
content = router.get(
self.path.strip('/'),
lambda d: ''
)(data)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(content)
def do_GET(self):
parsed_path = urlparse(self.path)
self.do(parsed_path.query)
def do_POST(self):
content_len = int(self.headers.getheader('content-length', 0))
post_body = self.rfile.read(content_len)
self.do(post_body)
return Handler
class Server(SocketServer.TCPServer):
allow_reuse_address = True
httpd = Server(("", PORT), create_handler({
'': index,
'stat': stat,
}))
print "serving at port", PORT
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.