Skip to content

Commit 7ae72c5

Browse files
committed
Update http_server.py
1 parent 0640431 commit 7ae72c5

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

assignments/session02/http_server.py

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,35 @@
11
import socket
22
import sys
3+
import os
4+
import mimetypes
35

4-
5-
def response_ok():
6+
def response_ok(body, mimetype):
67
"""returns a basic HTTP response"""
78
resp = []
89
resp.append("HTTP/1.1 200 OK")
9-
resp.append("Content-Type: text/plain")
10+
resp.append("Content-Type: {0}".format(mimetype))
1011
resp.append("")
11-
resp.append("this is a pretty minimal response")
12+
resp.append(body)
1213
return "\r\n".join(resp)
1314

15+
def resolve_uri(uri):
16+
base = 'webroot'
17+
fileName = os.path.join(base, uri.lstrip('/'))
18+
if os.path.isfile(filename):
19+
mimetype = mimetypes.guess_type(fileName)[0]
20+
body = open(filename, 'rb').read()
21+
return body, mimetype
22+
elif os.path.isdir(fileName):
23+
bk = "\n".join(os.listdir(fileName))
24+
return bk, 'text/ plain'
25+
else:
26+
return 'File Not Found'
27+
28+
def response_not_found():
29+
resp = []
30+
resp.append("HTTP/1.1 404 Not Found")
31+
resp.append("")
32+
return "\r\n".join(resp)
1433

1534
def response_method_not_allowed():
1635
"""returns a 405 Method Not Allowed response"""
@@ -19,13 +38,13 @@ def response_method_not_allowed():
1938
resp.append("")
2039
return "\r\n".join(resp)
2140

22-
2341
def parse_request(request):
2442
first_line = request.split("\r\n", 1)[0]
2543
method, uri, protocol = first_line.split()
2644
if method != "GET":
2745
raise NotImplementedError("We only accept GET")
2846
print >>sys.stderr, 'request is okay'
47+
return uri
2948

3049

3150
def server():
@@ -50,11 +69,17 @@ def server():
5069
break
5170

5271
try:
53-
parse_request(request)
72+
uri = parse_request(request)
73+
body, mimetype = resolve_uri(uri)
74+
5475
except NotImplementedError:
5576
response = response_method_not_allowed()
77+
78+
except ValueError:
79+
response = response_not_found()
80+
5681
else:
57-
response = response_ok()
82+
response = response_ok(body, mime)
5883

5984
print >>sys.stderr, 'sending response'
6085
conn.sendall(response)

0 commit comments

Comments
 (0)