server_registr.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. from http.server import BaseHTTPRequestHandler, HTTPServer
  2. import xml.etree.ElementTree as ET
  3. import os
  4. import json
  5. HOST_NAME = 'localhost'
  6. PORT_NUMBER = 8000
  7. class MyHandler(BaseHTTPRequestHandler):
  8. def do_POST(self):
  9. if self.path == '/save_user':
  10. self.handle_registration()
  11. elif self.path == '/login':
  12. self.handle_login()
  13. elif self.path == '/get_user':
  14. self.handle_get_user()
  15. elif self.path == '/saves_user':
  16. self.handle_update_user()
  17. else:
  18. self.send_error(404, 'Not Found')
  19. def handle_registration(self):
  20. # Получаем XML-данные из запроса
  21. content_length = int(self.headers['Content-Length'])
  22. xml_data = self.rfile.read(content_length).decode('utf-8')
  23. # Парсим XML-данные
  24. root = ET.fromstring(xml_data)
  25. # Извлекаем информацию из XML
  26. name = root.find('name').text
  27. phone = root.find('phone').text
  28. email = root.find('email').text
  29. code = root.find('code').text
  30. password = root.find('password').text
  31. # Сохраняем данные в файл registrations.xml
  32. with open('registrations.xml', 'a', encoding='utf-8') as f:
  33. f.write(f"""
  34. <user>
  35. <name>{name}</name>
  36. <phone>{phone}</phone>
  37. <email>{email}</email>
  38. <code>{code}</code>
  39. <password>{password}</password>
  40. </user>
  41. """)
  42. # Отправляем ответ на AJAX-запрос
  43. self.send_response(200)
  44. self.send_header('Content-type', 'text/plain')
  45. self.send_header('Access-Control-Allow-Origin', '*')
  46. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  47. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  48. self.end_headers()
  49. self.wfile.write(bytes('Данные успешно записаны', 'utf-8'))
  50. def do_OPTIONS(self):
  51. self.send_response(200)
  52. self.send_header('Access-Control-Allow-Origin', '*')
  53. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  54. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  55. self.end_headers()
  56. def handle_login(self):
  57. content_length = int(self.headers['Content-Length'])
  58. body = self.rfile.read(content_length).decode('utf-8')
  59. data = json.loads(body)
  60. email = data['email']
  61. password = data['password']
  62. # Чтение XML-файла
  63. tree = ET.parse('registrations.xml')
  64. root = tree.getroot()
  65. # Поиск пользователя по email
  66. user_found = False
  67. for user in root.findall('user'):
  68. if user.find('email').text == email:
  69. if user.find('password').text == password:
  70. user_found = True
  71. self.send_response(200)
  72. self.send_header('Content-type', 'text/plain')
  73. self.send_header('Access-Control-Allow-Origin', '*')
  74. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  75. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  76. self.end_headers()
  77. self.wfile.write(bytes('Вы успешно авторизованы!', 'utf-8'))
  78. break
  79. else:
  80. self.send_response(401)
  81. self.send_header('Content-type', 'text/plain')
  82. self.send_header('Access-Control-Allow-Origin', '*')
  83. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  84. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  85. self.end_headers()
  86. self.wfile.write(bytes('Неверный пароль', 'utf-8'))
  87. break
  88. if not user_found:
  89. self.send_response(404)
  90. self.send_header('Content-type', 'text/plain')
  91. self.send_header('Access-Control-Allow-Origin', '*')
  92. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  93. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  94. self.end_headers()
  95. self.wfile.write(bytes('Пользователь не существует', 'utf-8'))
  96. def do_OPTIONS(self):
  97. self.send_response(200)
  98. self.send_header('Access-Control-Allow-Origin', '*')
  99. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  100. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  101. self.end_headers()
  102. def handle_get_user(self):
  103. content_length = int(self.headers['Content-Length'])
  104. body = self.rfile.read(content_length).decode('utf-8')
  105. data = json.loads(body)
  106. email = data['email']
  107. tree = ET.parse('registrations.xml')
  108. root = tree.getroot()
  109. user_found = False
  110. for user in root.findall('user'):
  111. if user.find('email').text == email:
  112. user_found = True
  113. user_data = {
  114. 'name': user.find('name').text,
  115. 'surname': user.find('surname').text,
  116. 'patronymic': user.find('patronymic').text,
  117. 'phone': user.find('phone').text,
  118. 'email': user.find('email').text,
  119. 'code': user.find('code').text,
  120. 'password': user.find('password').text
  121. }
  122. self.send_response(200)
  123. self.send_header('Content-type', 'application/json')
  124. self.send_header('Access-Control-Allow-Origin', '*')
  125. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  126. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  127. self.end_headers()
  128. self.wfile.write(bytes(json.dumps(user_data), 'utf-8'))
  129. break
  130. if not user_found:
  131. self.send_response(401)
  132. self.send_header('Content-type', 'text/plain')
  133. self.send_header('Access-Control-Allow-Origin', '*')
  134. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  135. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  136. self.end_headers()
  137. self.wfile.write(bytes('Пользователь не найден', 'utf-8'))
  138. def handle_update_user(self):
  139. content_length = int(self.headers['Content-Length'])
  140. body = self.rfile.read(content_length).decode('utf-8')
  141. data = json.loads(body)
  142. name = data['name']
  143. surname = data['surname']
  144. patronymic = data['patronymic']
  145. phone = data['phone']
  146. email = data['email']
  147. password = data['password']
  148. tree = ET.parse('registrations.xml')
  149. root = tree.getroot()
  150. user_found = False
  151. for user in root.findall('user'):
  152. if user.find('email').text == email:
  153. user_found = True
  154. user.find('name').text = name
  155. user.find('surname').text = surname
  156. user.find('patronymic').text = patronymic
  157. user.find('phone').text = phone
  158. user.find('email').text = email
  159. user.find('password').text = password
  160. tree.write('registrations.xml', encoding='utf-8', xml_declaration=True)
  161. self.send_response(200)
  162. self.send_header('Content-type', 'text/plain')
  163. self.send_header('Access-Control-Allow-Origin', '*')
  164. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  165. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  166. self.end_headers()
  167. self.wfile.write(bytes('Данные успешно обновлены!', 'utf-8'))
  168. break
  169. if not user_found:
  170. self.send_response(401)
  171. self.send_header('Content-type', 'text/plain')
  172. self.send_header('Access-Control-Allow-Origin', '*')
  173. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  174. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  175. self.end_headers()
  176. self.wfile.write(bytes('Пользователь не найден', 'utf-8'))
  177. if __name__ == '__main__':
  178. server = HTTPServer((HOST_NAME, PORT_NUMBER), MyHandler)
  179. print(f'Сервер запущен на http://{HOST_NAME}:{PORT_NUMBER}')
  180. try:
  181. server.serve_forever()
  182. except KeyboardInterrupt:
  183. server.server_close()
  184. print('Сервер остановлен')