11import socket
22import sys
3+ import os
34import traceback
45
6+
57def response_ok (body = b"This is a minimal response" , mimetype = b"text/plain" ):
68 """
79 returns a basic HTTP response
@@ -16,24 +18,36 @@ def response_ok(body=b"This is a minimal response", mimetype=b"text/plain"):
1618 Content-Type: text/html\r \n
1719 \r \n
1820 <html><h1>Welcome:</h1></html>\r \n
19- '''
2021 """
21-
22- # TODO: Implement response_ok
23- return b""
22+ print (mimetype )
23+ print (body )
24+ response = f"""HTTP/1.1 200 OK\r
25+ Content-Type:{ mimetype } \r \n \r
26+ <html><body>{ body } </body></html>\r
27+ """
28+ # response = "HTTP/1.1 200 OK\r\n"
29+ # response += "Content-Type:{}\r\n".format(mimetype)
30+ # response += "\r\n"
31+ # response += "html><body>{}</body></html>\r\n".format(body)
32+
33+ return response .encode ()
2434
2535def response_method_not_allowed ():
2636 """Returns a 405 Method Not Allowed response"""
2737
28- # TODO: Implement response_method_not_allowed
29- return b""
38+ response = f"""HTTP/1.1 405\r
39+ Content-Type: text/plain\r \n \r
40+ <html><body>Method Not Allowed</body></html>\r """
41+ return response .encode ()
3042
3143
3244def response_not_found ():
3345 """Returns a 404 Not Found response"""
3446
35- # TODO: Implement response_not_found
36- return b""
47+ response = f"""HTTP/1.1 404\r
48+ Content-Type: text/plain\r \n \r
49+ <html><body>Not Found</body></html>\r """
50+ return response .encode ()
3751
3852
3953def parse_request (request ):
@@ -44,8 +58,13 @@ def parse_request(request):
4458 NotImplementedError if the method of the request is not GET.
4559 """
4660
47- # TODO: implement parse_request
48- return ""
61+ method , path , version = request .split ("\r \n " )[0 ].split (" " )
62+
63+ if method != "GET" :
64+ raise NotImplementedError
65+
66+ return path
67+
4968
5069def response_path (path ):
5170 """
@@ -74,10 +93,34 @@ def response_path(path):
7493 response_path('/a_page_that_doesnt_exist.html') -> Raises a NameError
7594
7695 """
77-
96+ content = ""
97+ mime_type = ""
98+ path = f"webroot{ path } "
99+ if not os .path .exists (path ):
100+ raise NameError
78101 # TODO: Raise a NameError if the requested content is not present
79102 # under webroot.
80103
104+
105+ if os .path .isdir (path ):
106+ dir_list = os .listdir (path )
107+ # dir_byte = "".join([str(elem + ", ") for elem in dir_list]).encode('utf8')
108+ print (dir_list )
109+ content = '' .join (dir_list ).encode ()
110+ mime_type = b"text/plain"
111+
112+ print (content )
113+
114+ if os .path .isfile (path ):
115+ types = {".jpg" : "image/jpeg" , ".png" : "image/png" , ".html" : "text/html" , ".ico" : "image/vnd.microsoft.icon" , ".txt" : "text/plain" }
116+ name , extension = os .path .splitext (path )
117+ mime_type = types .get (extension )
118+ print (mime_type )
119+
120+ with open (path , 'rt' ) as file :
121+ content = file .read ()
122+
123+
81124 # TODO: Fill in the appropriate content and mime_type give the path.
82125 # See the assignment guidelines for help on "mapping mime-types", though
83126 # you might need to create a special case for handling make_time.py
@@ -86,11 +129,92 @@ def response_path(path):
86129 # result of executing `make_time.py`. But you need only return the
87130 # CONTENTS of `make_time.py`.
88131
89- content = b"not implemented"
90- mime_type = b"not implemented"
132+ # content = b"not implemented"
133+ # mime_type = b"not implemented"
91134
92135 return content , mime_type
136+ # except NameError:
137+ # response = response_not_found()
138+ # # conn.sendall(response)
139+
140+
141+ # def server(log_buffer=sys.stderr):
142+ # address = ('127.0.0.1', 10000)
143+ # sock = socket.socket(socket.AF_INET,
144+ # socket.SOCK_STREAM,
145+ # socket.IPPROTO_TCP)
146+ # sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # permit reuse of local addresses for this socket
147+ # print("making a server on {0}:{1}".format(*address), file=log_buffer)
148+ # sock.bind(address)
149+ # sock.listen(1)
150+
151+ # try:
152+ # while True:
153+ # print('waiting for a connection', file=log_buffer)
154+ # conn, addr = sock.accept() # blocking
155+ # try:
156+ # print('connection - {0}:{1}'.format(*addr), file=log_buffer)
157+
158+ # request = ''
159+ # while True:
160+ # data = conn.recv(1024)
161+ # request += data.decode('utf8')
162+
163+ # if '\r\n\r\n' in request:
164+ # break
165+
93166
167+ # print("Request received:\n{}\n\n".format(request))
168+
169+
170+ # path = parse_request(request)
171+ # # TODO: Use parse_request to retrieve the path from the request.
172+
173+ # content, mime_type = response_path(path)
174+ # # print(content)
175+ # # print(mime_type)
176+
177+ # # TODO: Use response_path to retrieve the content and the mimetype,
178+ # # based on the request path.
179+ # # response = response_ok(
180+ # # body=content,
181+ # # mimetype=mime_type
182+ # # )
183+ # response = response_ok()
184+
185+ # # TODO; If parse_request raised a NotImplementedError, then let
186+ # # response be a method_not_allowed response. If response_path raised
187+ # # a NameError, then let response be a not_found response. Else,
188+ # # use the content and mimetype from response_path to build a
189+ # # response_ok.
190+ # # response = response_ok(
191+ # # body=b"Welcome to my web server",
192+ # # mimetype=b"text/plain"
193+ # # )
194+
195+
196+ # # response = response_ok(
197+ # # body=b"Welcome to my web server",
198+ # # mimetype=b"text/plain"
199+ # # )
200+
201+ # conn.sendall(response)
202+
203+ # except NotImplementedError:
204+ # response = response_method_not_allowed()
205+ # except NameError:
206+ # response = response_not_found()
207+ # except:
208+ # traceback.print_exc()
209+ # finally:
210+ # pass
211+ # # conn.close()
212+
213+ # except KeyboardInterrupt:
214+ # sock.close()
215+ # return
216+ # except:
217+ # traceback.print_exc()
94218
95219def server (log_buffer = sys .stderr ):
96220 address = ('127.0.0.1' , 10000 )
@@ -119,20 +243,26 @@ def server(log_buffer=sys.stderr):
119243 print ("Request received:\n {}\n \n " .format (request ))
120244
121245 # TODO: Use parse_request to retrieve the path from the request.
122-
246+ path = parse_request ( request )
123247 # TODO: Use response_path to retrieve the content and the mimetype,
124248 # based on the request path.
125-
249+ content , mime_type = response_path ( path )
126250 # TODO; If parse_request raised a NotImplementedError, then let
127251 # response be a method_not_allowed response. If response_path raised
128252 # a NameError, then let response be a not_found response. Else,
129253 # use the content and mimetype from response_path to build a
130254 # response_ok.
131255 response = response_ok (
132- body = b"Welcome to my web server" ,
133- mimetype = b"text/plain"
256+ body = content ,
257+ mimetype = mime_type
134258 )
135-
259+ print (response )
260+ conn .sendall (response )
261+ except NotImplementedError :
262+ response = response_method_not_allowed ()
263+ conn .sendall (response )
264+ except NameError :
265+ response = response_not_found ()
136266 conn .sendall (response )
137267 except :
138268 traceback .print_exc ()
@@ -146,7 +276,13 @@ def server(log_buffer=sys.stderr):
146276 traceback .print_exc ()
147277
148278
279+
149280if __name__ == '__main__' :
281+ # response = response_ok(
282+ # body=b"Welcome to my web server",
283+ # mimetype=b"text/plain"
284+ # )
285+ # print(response)
150286 server ()
151287 sys .exit (0 )
152288
0 commit comments