Skip to content

Commit 6cc697e

Browse files
committed
Added exception handling to resolve_uri() and fixed the handling of files
1 parent f1c4f12 commit 6cc697e

File tree

1 file changed

+28
-17
lines changed

1 file changed

+28
-17
lines changed

resources/session02/homework/http_server.py

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,13 @@
66

77
def response_ok(body=b"this is a pretty minimal response", mimetype=b"text/plain"):
88
"""returns a basic HTTP response"""
9+
10+
body, mimetype = resolve_uri(body)
911
resp = []
1012
resp.append(b"HTTP/1.1 200 OK")
11-
resp.append(b"Content-Type: text/plain")
13+
resp.append(b"Content-Type: " + mimetype)
1214
resp.append(b"")
13-
resp.append(b"this is a pretty minimal response")
15+
resp.append(body)
1416
return b"\r\n".join(resp)
1517

1618

@@ -42,24 +44,33 @@ def resolve_uri(uri):
4244
"""This method should return appropriate content and a mime type"""
4345
contents = b''
4446
mimetype = b''
47+
directory = './webroot'
4548

46-
homedir = Path('/webroot')
47-
pathreq = homedir / uri # Attempt to resolve the requested directory
49+
if isinstance(uri, bytes):
50+
directory += str(uri.decode('utf8'))
51+
else:
52+
directory += str(uri)
4853

49-
if pathreq.exists():
50-
if pathreq.isdir():
51-
# The requested path maps to a directory. The content should be a
52-
# plain-text listing of the directory contents with a mimetype of text/plain.
53-
filelist = [files for files in pathreq.iterdir() if files.is_file()]
54-
contents = '\n'.join(filelist).encode('utf8')
55-
mimetype = b'text/plain'
54+
try:
55+
pathreq = Path(directory).resolve() # Attempt to resolve the requested directory
56+
57+
if pathreq.exists():
58+
if pathreq.is_dir():
59+
# The requested path maps to a directory. The content should be a
60+
# plain-text listing of the directory contents with a mimetype of text/plain.
61+
filelist = [str(files) for files in pathreq.iterdir() if files.is_file()]
62+
contents = '\n'.join(filelist).encode('utf8')
63+
mimetype = b'text/plain'
64+
else:
65+
# The requested path maps to a file
66+
contents = pathreq.read_bytes()
67+
mimetype = mimetypes.guess_type(str(pathreq))[0].encode('utf8')
5668
else:
57-
# The requested path maps to a file
58-
with open(pathreq, 'rb') as contents:
59-
mimetype = mimetypes.guess_type(str(pathreq))
60-
else:
61-
# URI request does not exist. Raise an exception
62-
raise NameError
69+
raise NameError("{} does not exist\n".format(pathreq))
70+
except FileNotFoundError:
71+
raise NameError("{} could not be resolved\n".format(directory))
72+
except:
73+
print("Unexpected error:{}\n".format(sys.exc_info()[0]))
6374

6475
return contents, mimetype
6576

0 commit comments

Comments
 (0)