11import socket
22import sys
33import traceback
4+ import mimetypes
5+ import os
46
5- def response_ok (body = b"This is a minimal response" , mimetype = b"text/plain" ):
7+
8+ def response_ok (body = b"Welcome to my web server" , mimetype = b"text/plain" ):
69 """
710 returns a basic HTTP response
811 Ex:
@@ -19,21 +22,33 @@ def response_ok(body=b"This is a minimal response", mimetype=b"text/plain"):
1922 '''
2023 """
2124
22- # TODO: Implement response_ok
23- return b""
25+ return b"\r \n " .join ([
26+ b"HTTP/1.1 200 OK" ,
27+ b"Content-Type: " + mimetype ,
28+ b"" ,
29+ body ,
30+ ])
31+
2432
2533def response_method_not_allowed ():
2634 """Returns a 405 Method Not Allowed response"""
2735
28- # TODO: Implement response_method_not_allowed
29- return b""
36+ return b"\r \n " .join ([
37+ b"HTTP/1.1 405 Method Not Allowed" ,
38+ b"" ,
39+ b"You can't do that on this server!"
40+ ])
3041
3142
3243def response_not_found ():
3344 """Returns a 404 Not Found response"""
3445
3546 # TODO: Implement response_not_found
36- return b""
47+ return b"\r \n " .join ([
48+ b"HTTP/1.1 404 Page Not Found" ,
49+ b"" ,
50+ b"Sorry page not found!"
51+ ])
3752
3853
3954def parse_request (request ):
@@ -44,8 +59,12 @@ def parse_request(request):
4459 NotImplementedError if the method of the request is not GET.
4560 """
4661
47- # TODO: implement parse_request
48- return ""
62+ method , path , version = request .split ("\r \n " )[0 ].split (" " )
63+
64+ if method != "GET" :
65+ raise NotImplementedError
66+ return path
67+
4968
5069def response_path (path ):
5170 """
@@ -74,20 +93,41 @@ def response_path(path):
7493 response_path('/a_page_that_doesnt_exist.html') -> Raises a NameError
7594
7695 """
96+ home_dir = "/home/dan/cert/scripts/py230/03_Lesson/assignment/socket-http-server/webroot"
97+ abs_path = home_dir + path
98+
99+ try :
100+ # TODO: Fill in the appropriate content and mime_type give the path.
101+ # See the assignment guidelines for help on "mapping mime-types", though
102+ # you might need to create a special case for handling make_time.py
103+ if os .path .isdir (abs_path ):
104+ # directory
105+ mime_type = b"text/plain"
106+ lst = os .listdir (abs_path )
107+ content = ""
108+ for item in lst :
109+ content += " {}," .format (item )
110+ elif os .path .isfile (abs_path ):
111+ # file
112+ mime_type = mimetypes .guess_type (path )[0 ]
113+ content = b""
114+ with open (abs_path , "rb" ) as f :
115+ byte = f .read (1 )
116+ while byte :
117+ content += byte
118+ byte = f .read (1 )
77119
78120 # TODO: Raise a NameError if the requested content is not present
79121 # under webroot.
122+ except NameError :
123+ response_not_found ()
80124
81- # TODO: Fill in the appropriate content and mime_type give the path.
82- # See the assignment guidelines for help on "mapping mime-types", though
83- # you might need to create a special case for handling make_time.py
84- #
85125 # If the path is "make_time.py", then you may OPTIONALLY return the
86126 # result of executing `make_time.py`. But you need only return the
87127 # CONTENTS of `make_time.py`.
88-
89- content = b"not implemented"
90- mime_type = b"not implemented"
128+
129+ content = b"not implemented"
130+ mime_type = b"not implemented"
91131
92132 return content , mime_type
93133
@@ -114,30 +154,33 @@ def server(log_buffer=sys.stderr):
114154
115155 if '\r \n \r \n ' in request :
116156 break
117-
118157
119158 print ("Request received:\n {}\n \n " .format (request ))
120159
121- # TODO: Use parse_request to retrieve the path from the request.
122-
123- # TODO: Use response_path to retrieve the content and the mimetype,
124- # based on the request path.
125-
126- # TODO; If parse_request raised a NotImplementedError, then let
127- # response be a method_not_allowed response. If response_path raised
128- # a NameError, then let response be a not_found response. Else,
129- # use the content and mimetype from response_path to build a
130- # response_ok.
131- response = response_ok (
132- body = b"Welcome to my web server" ,
133- mimetype = b"text/plain"
134- )
160+ try :
161+ path = parse_request (request )
162+ # TODO: Use response_path to retrieve the content and the mimetype,
163+ # based on the request path.
164+ content , mtype = response_path (path )
165+ print (content , mtype )
166+
167+ # TODO; If parse_request raised a NotImplementedError, then let
168+ # response be a method_not_allowed response. If response_path raised
169+ # a NameError, then let response be a not_found response. Else,
170+ # use the content and mimetype from response_path to build a
171+ # response_ok.
172+ response = response_ok (
173+ body = content ,
174+ mimetype = mtype
175+ )
176+ except NotImplementedError :
177+ response = response_method_not_allowed ()
135178
136179 conn .sendall (response )
137180 except :
138181 traceback .print_exc ()
139182 finally :
140- conn .close ()
183+ conn .close ()
141184
142185 except KeyboardInterrupt :
143186 sock .close ()
@@ -149,5 +192,3 @@ def server(log_buffer=sys.stderr):
149192if __name__ == '__main__' :
150193 server ()
151194 sys .exit (0 )
152-
153-
0 commit comments