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):
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 = open(CSV_PATH, 'w')
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[1]] in count_map:
count_map[row[FIELDS[1]]] = count_map[row[FIELDS[1]]] + 1
else:
count_map[row[FIELDS[1]]] = 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 = {}
for k, l in parse_qs(query_string).items():
if len(l):
data[k] = l[0]
else:
data[k] = None
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.