Advertisement
Guest User

Untitled

a guest
Mar 17th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.00 KB | None | 0 0
  1. """
  2. Description : Omer Hasson's HTTP server
  3. Author : Omer Hasson
  4. Exercise Number : 4.4
  5. File Name : ex44
  6. Date : 2.3.18
  7. Version : 0.1
  8. """
  9.  
  10. import socket
  11. import re
  12. from urllib.request import urlopen
  13.  
  14. IP = '127.0.0.1'
  15. PORT = 8064
  16. DEFAULT_SOCKET_SIZE = 1024
  17.  
  18.  
  19. class Servers(object):
  20. """
  21. THE CLASS GETS the client socket
  22. """
  23.  
  24. def __init__(self, cs):
  25. self.client_socket = cs
  26.  
  27. @staticmethod
  28. def calculate_next(par_dict):
  29. """
  30. gets a number and calculate the next number.
  31. :param par_dict: dictionary of the parameters name and values.
  32. :return: next number.
  33. """
  34. print("doing some calculating...")
  35. print(str(par_dict))
  36. num = par_dict["num"]
  37. return num + 1
  38.  
  39. @staticmethod
  40. def calculate_area(par_dict):
  41. """
  42. gets hieght and width of a triangle and calculate the area.
  43. :param par_dict: dictionary of the parameters name and values.
  44. :return: the area of the triangle.
  45. """
  46. print("doing some calculating...")
  47. print(str(par_dict))
  48. height = par_dict["height"]
  49. width = par_dict["width"]
  50. return (height * width) / 2
  51.  
  52. @staticmethod
  53. def check_parameters(request):
  54. """
  55. checks if there are parameters.
  56. :return: true for yes false for no.
  57. """
  58. return request.find('?') > 0
  59.  
  60. def execute_request(self, request):
  61. """
  62. gets the url and executed the function in it.
  63. :param request: the requested URL
  64. :return: the result from the requested function
  65. *warning : the function can't be static!!!!!
  66. """
  67. print("in execute_request")
  68. request = request.split('?')
  69. func_name = request[0][1:].replace("-", "_")
  70. parameters_list = request[1].split('&')
  71. parameters_dict = {}
  72. for par in parameters_list:
  73. par = par.split('=')
  74. parameters_dict[par[0]] = int(par[1])
  75. return eval("self." + func_name)(parameters_dict)
  76.  
  77. # this defunction is the creator of the exercise 4 --->to make the next
  78. # exercises you need to make another def
  79. def running4(self):
  80. """
  81. this func is the creator of the exercise 4.4
  82. :return: the content&header to the main()
  83. """
  84. data = self.data_reciever(self.client_socket, DEFAULT_SOCKET_SIZE)
  85. print("request received")
  86. if data.startswith(b'GET'):
  87. data = re.search(b'GET(\s)(\S)+(\s)HTTP/1\.1\r\n', data)
  88. if data is not None:
  89. data = data.group(0)
  90. data = re.search(b'(\s)(\S)+', data)
  91. data = data.group(0).strip()
  92. print("after 2nd group()" + str(data))
  93. # handle requests of functions and parameters
  94. if self.check_parameters(data.decode()):
  95. print("I found parameters")
  96. content = self.execute_request(data.decode())
  97. content = str(content).encode()
  98. # build the response
  99. header = "HTTP/1.1 200 OK\r\n" \
  100. "Content-Length: " + str(content.__len__()) + \
  101. "\r\n\r\n"
  102. to_send = header.encode() + content
  103. # the original code
  104. else:
  105. if data == b'/':
  106. with open('index.html', 'rb') as my_file:
  107. content = my_file.read()
  108. header = "HTTP/1.1 200 OK\r\n" \
  109. "Content-Length: " + \
  110. str(content.__len__()) + \
  111. "\r\n" \
  112. "Content-Type: " \
  113. + self.data_type(content) \
  114. + "\r\n" + "\r\n"
  115. to_send = header.encode() + content
  116. else:
  117. data = data.decode()
  118. data = data[1:]
  119. data = data.replace("/", "\\")
  120. content_type = ""
  121. if self.data_type(data) == 'txt' or \
  122. self.data_type(data) == 'html':
  123. content_type = 'text/html; charset=utf-8'
  124. elif self.data_type(data) == 'jpg':
  125. content_type = 'image/jpeg'
  126. elif self.data_type(data) == 'js':
  127. content_type = 'text/javascript; charset=UTF-8'
  128. elif self.data_type(data) == 'css':
  129. content_type = 'text/css'
  130. elif self.data_type(data) == 'ico':
  131. content_type = 'image/x-icon'
  132. with open(data, 'rb') as my_file:
  133. content = my_file.read()
  134. header = "HTTP/1.1 200 OK\r\n" \
  135. "Content-Length: " + str(content.__len__()) + \
  136. "\r\n" \
  137. "Content-Type: " + content_type + "\r\n" \
  138. "\r\n"
  139. to_send = header.encode() + content
  140. return to_send
  141. elif data.startswith(b'POST'):
  142. # finding the content length
  143. content_length_location = data.find(b'Content-Length:') + 16
  144. content_length = data[content_length_location:]
  145. end_of_content_length = content_length.find(b'\r\n')
  146. content_length = content_length[0:end_of_content_length:1]
  147. file_name_location = data.find(b'file-name=') + 10
  148. file_name = data[file_name_location:]
  149. end_of_file_name = file_name.find(b' ')
  150. file_name = file_name[0:end_of_file_name:1]
  151. print(file_name.decode())
  152. file_name = file_name.decode()
  153. file_name = r'C:\Users\User\PycharmProjects\FinaleProj\uploads\\'\
  154. + str(file_name)
  155. print(file_name)
  156. file_type = file_name[file_name.find('.') + 1:]
  157. content = self.data_reciever(self.client_socket,
  158. int(content_length))
  159. with open(file_name, 'wb') as log:
  160. log.write(bytes(content))
  161. header = "HTTP/1.1 200 OK\r\n" \
  162. "Content-Length: " + "0" + \
  163. "\r\n" \
  164. "Content-Type: " + str() + "\r\n" + "\r\n"
  165. to_send = header.encode('utf-8')
  166.  
  167. return to_send
  168.  
  169.  
  170. @staticmethod
  171. def data_type(typer):
  172. """
  173. getting the data file name and
  174. :return: the type of the file
  175. """
  176. if type(typer) is not str:
  177. typer = typer.decode()
  178. typer = re.search('\..[^.]+', typer)
  179. typer = typer.group(0).strip()
  180. typer = typer.replace(".", "")
  181. return typer
  182.  
  183. @staticmethod
  184. def data_reciever(client_socket, size):
  185. """
  186. gets the client socket and getting data from it
  187. :returns: the data from the client_socket
  188. """
  189. data = client_socket.recv(size)
  190. return data
  191.  
  192.  
  193. def main():
  194. print('start')
  195. # Open a socket and loop forever while waiting for clients
  196. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  197. server_socket.bind((IP, PORT))
  198. server_socket.listen(0)
  199. client_socket, address = server_socket.accept()
  200.  
  201. """infinity loop"""
  202. done = False
  203. while not done:
  204. # creating the class appearance
  205. server = Servers(client_socket)
  206. # making the exercise 4.4
  207. client_socket.send(server.running4())
  208.  
  209.  
  210. if __name__ == "__main__":
  211. # Call the main handler function
  212. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement