1
1
import socket
2
2
import sys
3
3
import traceback
4
+ import os .path
5
+ import mimetypes
4
6
5
7
def response_ok (body = b"This is a minimal response" , mimetype = b"text/plain" ):
6
8
"""
@@ -30,7 +32,7 @@ def response_method_not_allowed():
30
32
"""Returns a 405 Method Not Allowed response"""
31
33
32
34
return b"\r \n " .join ([
33
- b"HTTP/1.1 403 Method Not Allowed" ,
35
+ b"HTTP/1.1 405 Method Not Allowed" ,
34
36
b"" ,
35
37
b"You can't do that on this server!" ,
36
38
])
@@ -40,7 +42,11 @@ def response_not_found():
40
42
"""Returns a 404 Not Found response"""
41
43
42
44
# TODO: Implement response_not_found
43
- return b""
45
+ return b"\r \n " .join ([
46
+ b"HTTP/1.1 404 Page Not Found" ,
47
+ b"" ,
48
+ b"I could not find that page!" ,
49
+ ])
44
50
45
51
46
52
def parse_request (request ):
@@ -96,10 +102,26 @@ def response_path(path):
96
102
# If the path is "make_time.py", then you may OPTIONALLY return the
97
103
# result of executing `make_time.py`. But you need only return the
98
104
# CONTENTS of `make_time.py`.
99
-
100
- content = b"not implemented"
101
- mime_type = b"not implemented"
102
-
105
+ #1: The path indicates a FILE that exists inside of webroot.
106
+ #2: The path indicates a DIRECTORY that exists inside of webroot.
107
+ #3: The path does NOT indicate a FILE or DIRECTORY that exists inside of webroot
108
+ #If path was '/sample.txt'
109
+ absolute_path = os .path .join (os .getcwd (), "webroot" , path .strip ('/' ))
110
+ #Then absolute path is now 'C:\Users\navgill/pythonweb/socket-server-hw/socket-http-server-homework'
111
+ if os .path .isfile (absolute_path ):
112
+ content = b""
113
+ with open (absolute_path , "rb" ) as f :
114
+ byte = f .read (1 )
115
+ while byte != b"" :
116
+ content += byte
117
+ byte = f .read (1 )
118
+ mime_type = mimetypes .guess_type (absolute_path )[0 ].encode ()
119
+ elif os .path .isdir (absolute_path ):
120
+ # Option 1: content = str(os.listdir(absolute_path))
121
+ content = " " .join (os .listdir (absolute_path )).encode ()
122
+ mime_type = b"text/plain"
123
+ else :
124
+ raise NameError
103
125
return content , mime_type
104
126
105
127
@@ -134,16 +156,19 @@ def server(log_buffer=sys.stderr):
134
156
135
157
# TODO: Use response_path to retrieve the content and the mimetype,
136
158
# based on the request path.
159
+ body , mimetype = response_path (path )
137
160
138
161
# TODO:
139
162
# If response_path raised
140
163
# a NameError, then let response be a not_found response. Else,
141
164
# use the content and mimetype from response_path to build a
142
165
# response_ok.
143
166
response = response_ok (
144
- body = b"Welcome to my web server" ,
145
- mimetype = b"text/plain"
167
+ body = body ,
168
+ mimetype = mimetype
146
169
)
170
+ except NameError :
171
+ response = response_not_found ()
147
172
except NotImplementedError :
148
173
response = response_method_not_allowed ()
149
174
0 commit comments