Skip to content

Commit af49e65

Browse files
author
saschwafel
committed
Setting up initial resource detection for resolve_uri
1 parent c7b6ea5 commit af49e65

File tree

9 files changed

+412
-63
lines changed

9 files changed

+412
-63
lines changed

assignments/session05/http_server.py

Lines changed: 111 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,99 +1,149 @@
1+
import mimetypes
2+
import os
13
import socket
24
import sys
35

6+
#print >>sys.stderr, sys.path[0]
7+
server_path = sys.path[0]
48

5-
def server(log_buffer=sys.stderr):
6-
address = ('127.0.0.1', 8080)
9+
def response_ok():
10+
"""returns a basic HTTP response"""
11+
#directory = os.getcwd()
12+
#print >>sys.stderr, directory
13+
#print >>sys.stderr, sys.path[0]
14+
resp = []
15+
resp.append("HTTP/1.1 200 OK")
16+
resp.append("Content-Type: text/plain")
17+
resp.append("")
18+
resp.append("this is a pretty minimal response")
19+
return "\r\n".join(resp)
20+
21+
def response_method_not_allowed():
22+
"""returns a 405 Method Not Allowed response"""
23+
resp = []
24+
resp.append("HTTP/1.1 405 Method Not Allowed")
25+
resp.append("")
26+
return "\r\n".join(resp)
27+
28+
29+
def parse_request(request):
30+
first_line = request.split("\r\n", 1)[0]
31+
method, uri, protocol = first_line.split()
32+
print >>sys.stderr, 'This is the URI: ', uri
33+
if method != "GET":
34+
raise NotImplementedError("We only accept GET")
35+
print >>sys.stderr, 'request is okay'
36+
return uri
37+
38+
def resolve_uri(uri):
39+
40+
home_dir = 'webroot'
41+
42+
print 'uri is: ', uri
43+
44+
print 'current dir is: ', os.getcwd()
45+
46+
#Make sure we're in the right directory
47+
if os.getcwd() == server_path:
48+
49+
#print 'switching from', os.getcwd()
50+
os.chdir(home_dir)
51+
#print 'New directory: ', os.getcwd()
52+
53+
#Remove leading slash and turn resource into an absolute path
54+
path_to_resource = os.path.join(str(os.getcwd()),str(uri.strip('/')))
55+
56+
print 'The Path to the resource is: ', path_to_resource
57+
58+
#Guess the mimetype of the resource
59+
mimetype_guess = mimetypes.guess_type(uri)
60+
61+
print 'It looks like the mimetype is: ', mimetypes.guess_type(uri)[0]
62+
63+
#If this is a directory, set mimetype
64+
if os.path.isdir(path_to_resource):
65+
print '\nThis is a directory!\n'
66+
mimetype_guess = 'text/plain'
67+
68+
#begin formulating the response
69+
resp = []
70+
resp.append("HTTP/1.1 200 OK")
71+
resp.append("Content-Type: text/plain")
72+
73+
#Add the guessed Mimetype
74+
resp.append("Content-Type: {}".format(mimetype_guess[0]))
75+
76+
#Adding necessary blank line
77+
resp.append("")
78+
79+
#Print each Entry if the URI is a directory
80+
if os.path.isdir(path_to_resource):
81+
[resp.append(i) for i in os.listdir(path_to_resource)]
82+
#resp.append(os.listdir(path_to_resource))
83+
84+
#resp.append("This is where your code will show! ")
85+
return "\r\n".join(resp)
86+
87+
#pass
88+
89+
def response_not_found():
90+
"""returns a 404 - Not Found response"""
91+
resp = []
92+
resp.append("HTTP/1.1 404 Not Found!")
93+
resp.append("")
94+
return "\r\n".join(resp)
95+
96+
def server():
97+
address = ('127.0.0.1', 10000)
798
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
899
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
9-
print >>log_buffer, "making a server on {0}:{1}".format(*address)
100+
print >>sys.stderr, "making a server on %s:%s" % address
10101
sock.bind(address)
11102
sock.listen(1)
12103

13104
try:
14105
while True:
15-
print >>log_buffer, 'waiting for a connection'
106+
print >>sys.stderr, 'waiting for a connection'
16107
conn, addr = sock.accept() # blocking
17108
try:
18-
print >>log_buffer, 'connection - {0}:{1}'.format(*addr)
19-
109+
print >>sys.stderr, 'connection - %s:%s' % addr
20110
request = ""
21-
22111
while True:
23-
24112
data = conn.recv(1024)
25-
26-
request+=data
27-
28-
if len(data) < 1024:
113+
request += data
114+
if len(data) < 1024 or not data:
29115
break
30116

31117
try:
32-
33118
uri = parse_request(request)
34-
35119
except NotImplementedError:
36120
response = response_method_not_allowed()
37-
38121
else:
122+
# replace this line with the following once you have
123+
# written resolve_uri
39124

40-
content, _type = resolve_uri(uri)
41-
42-
try:
43-
response = response_ok(content, type)
125+
response = resolve_uri(uri)
44126

45-
except NameError:
46-
response = response_not_found()
127+
#response = response_ok()
47128

48-
print >>log_buffer, 'sending response'
49-
50-
conn.sendall(response)
129+
# content, type = resolve_uri(uri) # change this line
51130

52-
#print >>log_buffer, 'received "{0}"'.format(data)
131+
## uncomment this try/except block once you have fixed
132+
## response_ok and added response_not_found
133+
# try:
134+
# response = response_ok(content, type)
135+
# except NameError:
136+
# response = response_not_found()
53137

54-
# if data:
55-
# msg = 'sending data back to client'
56-
# print >>log_buffer, msg
57-
# conn.sendall(data)
58-
# else:
59-
# msg = 'no more data from {0}:{1}'.format(*addr)
60-
# print >>log_buffer, msg
61-
# break
138+
print >>sys.stderr, 'sending response'
139+
conn.sendall(response)
62140
finally:
63141
conn.close()
64142

65143
except KeyboardInterrupt:
66144
sock.close()
67145
return
68146

69-
def parse_request(request):
70-
first_line = request.split("\r\n", 1)[0]
71-
method, uri, protocol = first_line.split()
72-
if method != "GET":
73-
74-
raise NotImplementedError('This is not a GET request')
75-
76-
print >>sys.stderr, 'request is okay'
77-
return uri
78-
79-
80-
81-
def response_method_not_allowed():
82-
"""returns a method_not_allowed HTTP response"""
83-
resp = []
84-
resp.append("HTTP/1.1 405 Method Not Allowed")
85-
resp.append("")
86-
return "\r\n".join(resp)
87-
88-
def response_ok():
89-
"""returns a basic HTTP response"""
90-
resp = []
91-
resp.append("HTTP/1.1 200 OK")
92-
resp.append("Content-Type: text/plain")
93-
resp.append("")
94-
resp.append("this is a pretty minimal response")
95-
return "\r\n".join(resp)
96-
97147

98148
if __name__ == '__main__':
99149
server()
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import socket
2+
import sys
3+
4+
5+
def client(msg):
6+
server_address = ('localhost', 10000)
7+
sock = socket.socket(
8+
socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP
9+
)
10+
print >>sys.stderr, 'connecting to {0} port {1}'.format(*server_address)
11+
sock.connect(server_address)
12+
response = ''
13+
done = False
14+
bufsize = 1024
15+
try:
16+
print >>sys.stderr, 'sending "{0}"'.format(msg)
17+
sock.sendall(msg)
18+
while not done:
19+
chunk = sock.recv(bufsize)
20+
if len(chunk) < bufsize:
21+
done = True
22+
response += chunk
23+
print >>sys.stderr, 'received "{0}"'.format(response)
24+
finally:
25+
print >>sys.stderr, 'closing socket'
26+
sock.close()
27+
return response
28+
29+
30+
if __name__ == '__main__':
31+
if len(sys.argv) != 2:
32+
usg = '\nusage: python echo_client.py "this is my message"\n'
33+
print >>sys.stderr, usg
34+
sys.exit(1)
35+
36+
msg = sys.argv[1]
37+
client(msg)

0 commit comments

Comments
 (0)