Skip to content

finished assignment #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 73 additions & 38 deletions http_server.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import socket
import sys
import traceback
import os.path
import mimetypes
from os import listdir
import subprocess
import os

def response_ok(body=b"This is a minimal response", mimetype=b"text/plain"):
"""
Expand All @@ -19,21 +24,30 @@ def response_ok(body=b"This is a minimal response", mimetype=b"text/plain"):
'''
"""

# TODO: Implement response_ok
return b""
return b"\r\n".join([
b"HTTP/1.1 200 OK",
b"Content-Type: " + mimetype,
b"",
body
])

def response_method_not_allowed():
"""Returns a 405 Method Not Allowed response"""

# TODO: Implement response_method_not_allowed
return b""

return b"\r\n".join([
b"HTTP/1.1 405 Method Not Allowed",
b"",
b"You can't do that on this server!"
])

def response_not_found():
"""Returns a 404 Not Found response"""

# TODO: Implement response_not_found
return b""
return b"\r\n".join([
b"HTTP/1.1 404 Method Not Allowed",
b"",
b"Request not found!"
])


def parse_request(request):
Expand All @@ -44,8 +58,12 @@ def parse_request(request):
NotImplementedError if the method of the request is not GET.
"""

# TODO: implement parse_request
return ""
method, path, version = request.split("\r\n")[0].split(" ")

if method != "GET":
raise NotImplementedError

return path

def response_path(path):
"""
Expand Down Expand Up @@ -74,22 +92,38 @@ def response_path(path):
response_path('/a_page_that_doesnt_exist.html') -> Raises a NameError

"""

# TODO: Raise a NameError if the requested content is not present
# under webroot.

# TODO: Fill in the appropriate content and mime_type give the path.
# See the assignment guidelines for help on "mapping mime-types", though
# you might need to create a special case for handling make_time.py
#
# If the path is "make_time.py", then you may OPTIONALLY return the
# result of executing `make_time.py`. But you need only return the
# CONTENTS of `make_time.py`.

path = "webroot" + path
content = b"not implemented"
mime_type = b"not implemented"
mimetype = b"not implemented"

try:
#if it is a directory, then display contents with mimetype `text/plain`
if os.path.isdir(path):
content = "\r\n".join([file for file in listdir(path)]).encode()

mimetype = b"text/plain"

#if its a python file, then get the results
elif path.endswith('.py'):

mimetype = b'text/html'
cmd = subprocess.run(["python", f"{path}"], capture_output=True)
content = cmd.stdout#.decode() # need bytes not string

# else read from the file
else:
with open(path, "rb") as file:
content = file.read()

file_type = mimetypes.guess_type(path)[0]
mimetype = file_type.encode("utf-8")

# raise name error if content is not present
except FileNotFoundError:
raise NameError

return content, mime_type
return content, mimetype


def server(log_buffer=sys.stderr):
Expand All @@ -115,33 +149,34 @@ def server(log_buffer=sys.stderr):
if '\r\n\r\n' in request:
break


print("Request received:\n{}\n\n".format(request))

# TODO: Use parse_request to retrieve the path from the request.

# TODO: Use response_path to retrieve the content and the mimetype,
# based on the request path.

# TODO; If parse_request raised a NotImplementedError, then let
# response be a method_not_allowed response. If response_path raised
# a NameError, then let response be a not_found response. Else,
# use the content and mimetype from response_path to build a
# response_ok.
response = response_ok(
body=b"Welcome to my web server",
mimetype=b"text/plain"
)

try:
path = parse_request(request)
content, mimetype = response_path(path)
response = response_ok(body=content, mimetype=mimetype)

except NotImplementedError:
response = response_method_not_allowed()

except NameError:
response = response_not_found()

conn.sendall(response)

except KeyboardInterrupt:
raise KeyboardInterrupt

except:
traceback.print_exc()

finally:
conn.close()

except KeyboardInterrupt:
sock.close()
return

except:
traceback.print_exc()

Expand Down