Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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(data[field] for field in FIELDS)+'\n')
return '''
<form method="POST">
<input type="submit" />
'{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 '''
border-collapse: collapse;
border: 1px solid grey;
'<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):
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')
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(
lambda d: ''
httpd = make_server('', PORT, app)
print("serving at port", PORT)
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.