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