Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# http://slides.com/robinchew/deck
from collections import defaultdict
from textwrap import dedent
from urllib.parse import urlparse, parse_qs
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server
import csv
import os
import sys
PORT = int(sys.argv[1])
CSV_PATH = 'students.csv'
FIELDS = ('Name', 'Degree',)
def index(data):
if set(data.keys()) == set(FIELDS):
csv_exists = os.path.isfile(CSV_PATH)
with open(CSV_PATH, 'a') as f:
if not csv_exists:
f = open(CSV_PATH, 'w')
f.write(','.join(FIELDS)+'\n')
f.write(','.join(data[field] for field in FIELDS)+'\n')
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):
degree_field = FIELDS[1]
count_map = defaultdict(int)
with open(CSV_PATH) as f:
for row in csv.DictReader(f):
count_map[row[degree_field]] += 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[1],
'</tr><tr>'.join(
'<td>{0}</td><td>{1}</td>'.format(value, count)
for value, count in count_map.items()
)
)
router = {
'': index,
'stat': stat,
}
def app(environ, start_response):
#setup_testing_defaults(environ)
path = environ['PATH_INFO']
method = environ['REQUEST_METHOD']
status = '200 OK'
headers = [('Content-type', 'text/html')]
start_response(status, headers)
if method == 'POST':
query_string = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH'])).decode('ascii')
else:
query_string = environ['QUERY_STRING']
data = {
k: l[0] if len(l) else None
for k, l in parse_qs(query_string).items()
}
return [router.get(
path.strip('/'),
lambda d: ''
)(data).encode('ascii')]
httpd = make_server('', PORT, app)
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.