Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Description : Omer Hasson's HTTP server
- Author : Omer Hasson
- Exercise Number : 4.4
- File Name : ex44
- Date : 2.3.18
- Version : 0.1
- """
- import socket
- import re
- from urllib.request import urlopen
- IP = '127.0.0.1'
- PORT = 8064
- DEFAULT_SOCKET_SIZE = 1024
- class Servers(object):
- """
- THE CLASS GETS the client socket
- """
- def __init__(self, cs):
- self.client_socket = cs
- @staticmethod
- def calculate_next(par_dict):
- """
- gets a number and calculate the next number.
- :param par_dict: dictionary of the parameters name and values.
- :return: next number.
- """
- print("doing some calculating...")
- print(str(par_dict))
- num = par_dict["num"]
- return num + 1
- @staticmethod
- def calculate_area(par_dict):
- """
- gets hieght and width of a triangle and calculate the area.
- :param par_dict: dictionary of the parameters name and values.
- :return: the area of the triangle.
- """
- print("doing some calculating...")
- print(str(par_dict))
- height = par_dict["height"]
- width = par_dict["width"]
- return (height * width) / 2
- @staticmethod
- def check_parameters(request):
- """
- checks if there are parameters.
- :return: true for yes false for no.
- """
- return request.find('?') > 0
- def execute_request(self, request):
- """
- gets the url and executed the function in it.
- :param request: the requested URL
- :return: the result from the requested function
- *warning : the function can't be static!!!!!
- """
- print("in execute_request")
- request = request.split('?')
- func_name = request[0][1:].replace("-", "_")
- parameters_list = request[1].split('&')
- parameters_dict = {}
- for par in parameters_list:
- par = par.split('=')
- parameters_dict[par[0]] = int(par[1])
- return eval("self." + func_name)(parameters_dict)
- # this defunction is the creator of the exercise 4 --->to make the next
- # exercises you need to make another def
- def running4(self):
- """
- this func is the creator of the exercise 4.4
- :return: the content&header to the main()
- """
- data = self.data_reciever(self.client_socket, DEFAULT_SOCKET_SIZE)
- print("request received")
- if data.startswith(b'GET'):
- data = re.search(b'GET(\s)(\S)+(\s)HTTP/1\.1\r\n', data)
- if data is not None:
- data = data.group(0)
- data = re.search(b'(\s)(\S)+', data)
- data = data.group(0).strip()
- print("after 2nd group()" + str(data))
- # handle requests of functions and parameters
- if self.check_parameters(data.decode()):
- print("I found parameters")
- content = self.execute_request(data.decode())
- content = str(content).encode()
- # build the response
- header = "HTTP/1.1 200 OK\r\n" \
- "Content-Length: " + str(content.__len__()) + \
- "\r\n\r\n"
- to_send = header.encode() + content
- # the original code
- else:
- if data == b'/':
- with open('index.html', 'rb') as my_file:
- content = my_file.read()
- header = "HTTP/1.1 200 OK\r\n" \
- "Content-Length: " + \
- str(content.__len__()) + \
- "\r\n" \
- "Content-Type: " \
- + self.data_type(content) \
- + "\r\n" + "\r\n"
- to_send = header.encode() + content
- else:
- data = data.decode()
- data = data[1:]
- data = data.replace("/", "\\")
- content_type = ""
- if self.data_type(data) == 'txt' or \
- self.data_type(data) == 'html':
- content_type = 'text/html; charset=utf-8'
- elif self.data_type(data) == 'jpg':
- content_type = 'image/jpeg'
- elif self.data_type(data) == 'js':
- content_type = 'text/javascript; charset=UTF-8'
- elif self.data_type(data) == 'css':
- content_type = 'text/css'
- elif self.data_type(data) == 'ico':
- content_type = 'image/x-icon'
- with open(data, 'rb') as my_file:
- content = my_file.read()
- header = "HTTP/1.1 200 OK\r\n" \
- "Content-Length: " + str(content.__len__()) + \
- "\r\n" \
- "Content-Type: " + content_type + "\r\n" \
- "\r\n"
- to_send = header.encode() + content
- return to_send
- elif data.startswith(b'POST'):
- # finding the content length
- content_length_location = data.find(b'Content-Length:') + 16
- content_length = data[content_length_location:]
- end_of_content_length = content_length.find(b'\r\n')
- content_length = content_length[0:end_of_content_length:1]
- file_name_location = data.find(b'file-name=') + 10
- file_name = data[file_name_location:]
- end_of_file_name = file_name.find(b' ')
- file_name = file_name[0:end_of_file_name:1]
- print(file_name.decode())
- file_name = file_name.decode()
- file_name = r'C:\Users\User\PycharmProjects\FinaleProj\uploads\\'\
- + str(file_name)
- print(file_name)
- file_type = file_name[file_name.find('.') + 1:]
- content = self.data_reciever(self.client_socket,
- int(content_length))
- with open(file_name, 'wb') as log:
- log.write(bytes(content))
- header = "HTTP/1.1 200 OK\r\n" \
- "Content-Length: " + "0" + \
- "\r\n" \
- "Content-Type: " + str() + "\r\n" + "\r\n"
- to_send = header.encode('utf-8')
- return to_send
- @staticmethod
- def data_type(typer):
- """
- getting the data file name and
- :return: the type of the file
- """
- if type(typer) is not str:
- typer = typer.decode()
- typer = re.search('\..[^.]+', typer)
- typer = typer.group(0).strip()
- typer = typer.replace(".", "")
- return typer
- @staticmethod
- def data_reciever(client_socket, size):
- """
- gets the client socket and getting data from it
- :returns: the data from the client_socket
- """
- data = client_socket.recv(size)
- return data
- def main():
- print('start')
- # Open a socket and loop forever while waiting for clients
- server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- server_socket.bind((IP, PORT))
- server_socket.listen(0)
- client_socket, address = server_socket.accept()
- """infinity loop"""
- done = False
- while not done:
- # creating the class appearance
- server = Servers(client_socket)
- # making the exercise 4.4
- client_socket.send(server.running4())
- if __name__ == "__main__":
- # Call the main handler function
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement