Skip to content

Commit b27fcde

Browse files
committed
Ready for homework.
0 parents  commit b27fcde

12 files changed

Lines changed: 551 additions & 0 deletions

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
*pycache*
2+
*solution*
3+
*.idea*

‎README.md‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# CLASS BASED SERVER
2+
3+
A class-based HTTP socket server.
4+
5+
Once you're done, you should be able to start the web server inside the homework directory using `python -u http_server.py` and then point your web browser at locations like:
6+
* http://localhost:10000/sample.txt
7+
* http://localhost:10000/a_web_page.html
8+
* http://localhost:10000/images/sample_1.png
9+
10+
and see the corresponding file located under homework/webroot. Take a moment to look into the homework/webroot and see these files. 
11+
12+
Inside this repository you'll find the http_server.py file. I've added enough stub code for the missing functions to let the server run. And there are more tests for you to make pass!
13+
14+
You do NOT need to execute the `make_time.py` Python file. When a web user visits `http://localhost:1000/make_time.py` you only need to _serve up_ the contents of that file. But if you'd like to take on a challenge, then you _can_ choose to execute the file and serve up the result of performing that execution.
15+
16+
17+
## Hints
18+
19+
* Because your server will be transmitting files as bytes, you might want to try searching for "reading a file as bytes in Python".
20+
* Your `get_content` method is going to be looking at the incoming path and checking whether the path represents a directory, a file, or none of the above. There are relevant methods in the [os.path](https://docs.python.org/3/library/os.path.html) module.
21+
* In some cases, you'll have to get a list of files inside of a directory and then turn that list into a bytestring. There's a method inside of [the os module](https://docs.python.org/3/library/os.html) that can help you address the first part of that problem. You'll then have to turn that list into a string and then a byte-string using techniques you've learned in this class and previous classes.
22+
* Your `get_mimetype` method will receive a path and return an appropriate mimetype. The [mimetypes.guess_type](https://docs.python.org/3.7/library/mimetypes.html) method might be useful. Try playing around with this method at the REPL and manipulating its return value until it matches what you want. For example:
23+
```python
24+
>>> import mimetypes
25+
>>> result = mimetypes.guess_type("foo/bar.png")
26+
>>> print(result)
27+
# ...
28+
```
29+
* Finally, your `get_content` method will be receiving `path` arguments such as "/a_sample_page.html". Suppose that you are running your server with the command `python http_server.py` from inside the `class-based-server` directory. Then if you have expressions like `os.path.isfile(path)` in your `response_path` method, these will be looking for a file named "a_sample_page.html" inside of your `class-based-server` directory. That file **doesn't exist**: the "a_sample_page.html" exists inside of the `webroot` directory. So as you're writing your `response_path` method, you're going to have to somehow modify the `path` variable to make python look for files _inside_ of the `webroot` directory.
30+
31+
## Use Your Tests
32+
33+
As you work your way through the steps outlined above, look at your tests. Write code that makes them pass.
34+
35+
There are integration tests that you can run with `python tests.py` and unit tests that you can run with `python unit-tests.py`. The unit tests test everything except for the server method.
36+
37+
You may find it helpful to work through the homework using either or both sets of tests. If you're not sure how to proceed, it may be easier to begin by running the unit tests and trying to make them pass one at a time.
38+
39+
## Going Further
40+
41+
To take this one step further, make the directory listings into clickable links: if you visit `http://localhost:10000/` then the list of files should be clickable links that take you to that file. And similarly if you visit `http://localhost:10000/images/` then the list of images should be clickable links.
42+
43+
If you want to accomplish this, you'll need to:
44+
* change the mime type for your directory listings from `text/plain` to `text/html`
45+
* know how to make an HTML link: a link in HTML looks like `<a href="/images/sample_1.png">arbitrary link text</a>`

‎http_server.py‎

Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
import socket
2+
import sys
3+
import traceback
4+
import os
5+
import mimetypes
6+
7+
class HttpServer():
8+
9+
@staticmethod
10+
def make_response(
11+
code,
12+
reason,
13+
body=b"",
14+
mimetype=b"text/plain"
15+
):
16+
"""
17+
returns a basic HTTP response
18+
Ex:
19+
make_response(
20+
b"200",
21+
b"OK",
22+
b"<html><h1>Welcome:</h1></html>",
23+
b"text/html"
24+
) ->
25+
26+
b'''
27+
HTTP/1.1 200 OK\r\n
28+
Content-Type: text/html\r\n
29+
\r\n
30+
<html><h1>Welcome:</h1></html>\r\n
31+
'''
32+
"""
33+
34+
return b"\r\n".join([
35+
b"HTTP/1.1 " + code + b" " + reason,
36+
b"Content-Type: " + mimetype,
37+
b"",
38+
body
39+
])
40+
41+
@staticmethod
42+
def get_path(request):
43+
"""
44+
Given the content of an HTTP request, return the _path_
45+
of that request.
46+
47+
For example, if request were:
48+
49+
'''
50+
GET /images/sample_1.png HTTP/1.1
51+
Host: localhost:1000
52+
53+
'''
54+
55+
Then you would return "/images/sample_1.png"
56+
"""
57+
58+
return "TODO: COMPLETE THIS" # TODO
59+
60+
61+
@staticmethod
62+
def get_mimetype(path):
63+
"""
64+
This method should return a suitable mimetype for the given `path`.
65+
66+
A mimetype is a short bytestring that tells a browser how to
67+
interpret the response body. For example, if the response body
68+
contains a web page then the mimetype should be b"text/html". If
69+
the response body contains a JPG image, then the mimetype would
70+
be b"image/jpeg".
71+
72+
Here are a few concrete examples:
73+
74+
get_mimetype('/a_web_page.html') -> b"text/html"
75+
76+
get_mimetype('/images/sample_1.png') -> b"image/png"
77+
78+
get_mimetype('/') -> b"text/plain"
79+
# A directory listing should have either a plain text mimetype
80+
# or a b"text/html" mimetype if you turn your directory listings
81+
# into web pages.
82+
83+
get_mimetype('/a_page_that_doesnt_exist.html') -> b"text/html"
84+
# This function should return an appropriate mimetype event
85+
# for files that don't exist.
86+
"""
87+
88+
if path.endswith('/'):
89+
return b"text/plain"
90+
else:
91+
return b"TODO: FINISH THE REST OF THESE CASES" # TODO
92+
93+
@staticmethod
94+
def get_content(path):
95+
"""
96+
This method should return the content of the file/directory
97+
indicated by `path`. For example, if path is `/a_web_page.html`
98+
then this function would return the contents of the file
99+
`webroot/a_web_page.html` as a byte string.
100+
101+
* If the requested path is a directory, then the content should
102+
be a plain-text listing of the contents of that directory.
103+
104+
* If the path is a file, it should return the contents of that
105+
file.
106+
107+
* If the indicated path doesn't exist inside of `webroot`, then
108+
raise a FileNotFoundError.
109+
110+
Here are some concrete examples:
111+
112+
Ex:
113+
get_content('/a_web_page.html') -> b"<html><h1>North Carolina..."
114+
# Returns the contents of `webroot/a_web_page.html`
115+
116+
get_content('/images/sample_1.png') -> b"A12BCF..."
117+
# Returns the contents of `webroot/images/sample_1.png`
118+
119+
get_content('/') -> images/, a_web_page.html, make_type.py,..."
120+
# Returns a directory listing of `webroot/`
121+
122+
get_content('/a_page_that_doesnt_exist.html')
123+
# The file `webroot/a_page_that_doesnt_exist.html`) doesn't exist,
124+
# so this should raise a FileNotFoundError.
125+
"""
126+
127+
return b"Not implemented!" # TODO: Complete this function.
128+
129+
def __init__(self, port):
130+
self.port = port
131+
132+
def serve(self):
133+
address = ('0.0.0.0', port)
134+
135+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
136+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
137+
138+
print("making a server on {0}:{1}".format(*address))
139+
print("Visit http://localhost:{}".format(port))
140+
141+
sock.bind(address)
142+
sock.listen(10)
143+
144+
try:
145+
while True:
146+
print('waiting for a connection')
147+
conn, addr = sock.accept() # blocks until a connection arrives
148+
try:
149+
print('connection - {0}:{1}'.format(*addr))
150+
151+
request = ''
152+
while True:
153+
data = conn.recv(1024)
154+
request += data.decode('utf8')
155+
156+
if '\r\n\r\n' in request:
157+
break
158+
159+
print("Request received:\n{}\n\n".format(request))
160+
161+
path = self.get_path(request)
162+
163+
try:
164+
body = self.get_content(path)
165+
mimetype = self.get_mimetype(path)
166+
167+
response = self.make_response(
168+
b"200", b"OK", body, mimetype
169+
)
170+
171+
except FileNotFoundError:
172+
body = b"Couldn't find the file you requested."
173+
mimetype = b"text/plain"
174+
175+
response = self.make_response(
176+
b"404", b"NOT FOUND", body, mimetype
177+
)
178+
179+
conn.sendall(response)
180+
except:
181+
traceback.print_exc()
182+
finally:
183+
conn.close()
184+
185+
except KeyboardInterrupt:
186+
sock.close()
187+
return
188+
except:
189+
traceback.print_exc()
190+
191+
192+
if __name__ == '__main__':
193+
try:
194+
port = int(sys.argv[1])
195+
except IndexError:
196+
port = 10000
197+
198+
server = HttpServer(port)
199+
server.serve()
200+

0 commit comments

Comments
 (0)