server.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. from http.server import BaseHTTPRequestHandler, HTTPServer
  2. from xml.etree import ElementTree as ET
  3. import json
  4. import random
  5. import smtplib
  6. import os
  7. from email.mime.text import MIMEText
  8. HOST_NAME = 'localhost'
  9. PORT_NUMBER = 8000
  10. # Глобальный объект сервера
  11. server = None
  12. class MyHandler(BaseHTTPRequestHandler):
  13. def do_POST(self):
  14. if self.path == 'http://localhost:8000/send_code':
  15. self.handle_send_code()
  16. elif self.path == 'http://localhost:8000/register':
  17. self.handle_registration()
  18. else:
  19. self.send_error(404, 'Not Found')
  20. def handle_send_code(self):
  21. content_length = int(self.headers['Content-Length'])
  22. body = self.rfile.read(content_length).decode('utf-8')
  23. data = json.loads(body)
  24. email = data['email']
  25. # Проверка на Gmail
  26. if not email.endswith('@gmail.com'):
  27. self.send_response(400)
  28. self.send_header('Content-type', 'text/plain')
  29. self.send_header('Access-Control-Allow-Origin', '*')
  30. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  31. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  32. self.end_headers()
  33. self.wfile.write(bytes('Пожалуйста, введите адрес электронной почты Gmail.', 'utf-8'))
  34. return
  35. code = str(random.randint(100000, 999999))
  36. try:
  37. msg = MIMEText(f'Ваш код подтверждения: {code}')
  38. msg['Subject'] = 'Код подтверждения'
  39. msg['From'] = 'damirka20051904@gmail.com' # Замените на ваш адрес
  40. msg['To'] = email
  41. with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
  42. server.login('damirka20051904@gmail.com', 'DaMiR_2005') # Замените на ваш логин и пароль
  43. server.sendmail('damirka20051904@gmail.com', email, msg.as_string())
  44. self.send_response(200)
  45. self.send_header('Content-type', 'text/plain')
  46. self.send_header('Access-Control-Allow-Origin', '*')
  47. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  48. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  49. self.end_headers()
  50. self.wfile.write(bytes('Код успешно отправлен', 'utf-8'))
  51. except Exception as e:
  52. self.send_response(500)
  53. self.send_header('Content-type', 'text/plain')
  54. self.send_header('Access-Control-Allow-Origin', '*')
  55. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  56. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  57. self.end_headers()
  58. self.wfile.write(bytes(f'Ошибка отправки кода: {e}', 'utf-8'))
  59. def handle_registration(self):
  60. # Получаем XML-данные из запроса
  61. content_length = int(self.headers['Content-Length'])
  62. xml_data = self.rfile.read(content_length).decode('utf-8')
  63. # Парсим XML-данные
  64. root = ET.fromstring(xml_data)
  65. # Извлекаем информацию из XML
  66. name = root.find('name').text
  67. phone = root.find('phone').text
  68. email = root.find('email').text
  69. code = root.find('code').text
  70. password = root.find('password').text
  71. # Сохраняем данные в файл users.xml
  72. with open('registrations.xml', 'a', encoding='utf-8') as f:
  73. f.write(f"""
  74. <user>
  75. <name>{name}</name>
  76. <phone>{phone}</phone>
  77. <email>{email}</email>
  78. <code>{code}</code>
  79. <password>{password}</password>
  80. </user>
  81. """)
  82. # Отправляем ответ на AJAX-запрос
  83. self.send_response(200)
  84. self.send_header('Content-type', 'text/plain')
  85. self.send_header('Access-Control-Allow-Origin', '*')
  86. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  87. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  88. self.end_headers()
  89. self.wfile.write(bytes('Данные успешно записаны', 'utf-8'))
  90. def do_OPTIONS(self):
  91. self.send_response(200)
  92. self.send_header('Access-Control-Allow-Origin', '*')
  93. self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
  94. self.send_header('Access-Control-Allow-Headers', 'Content-Type')
  95. self.end_headers()
  96. class MyHandler(BaseHTTPRequestHandler):
  97. def do_GET(self):
  98. if self.path == 'документы/Устав.docx':
  99. self.handle_file_download('Устав.docx')
  100. else:
  101. self.send_error(404, 'Not Found')
  102. def handle_file_download(self, filename):
  103. try:
  104. with open(filename, 'rb') as f:
  105. self.send_response(200)
  106. self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  107. self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
  108. self.end_headers()
  109. self.wfile.write(f.read())
  110. except FileNotFoundError:
  111. self.send_error(404, 'File not found')
  112. class MyHandler(BaseHTTPRequestHandler):
  113. def do_GET(self):
  114. if self.path == 'документы/Инструкция выгрузка подписи.docx':
  115. self.handle_file_download('Инструкция выгрузка подписи.docx')
  116. else:
  117. self.send_error(404, 'Not Found')
  118. def handle_file_download(self, filename):
  119. try:
  120. with open(filename, 'rb') as f:
  121. self.send_response(200)
  122. self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  123. self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
  124. self.end_headers()
  125. self.wfile.write(f.read())
  126. except FileNotFoundError:
  127. self.send_error(404, 'File not found')
  128. class MyHandler(BaseHTTPRequestHandler):
  129. def do_GET(self):
  130. if self.path == 'документы/РП_Данные_ГИС_ЖКХ_2_1_v1.docx':
  131. self.handle_file_download('РП_Данные_ГИС_ЖКХ_2_1_v1.docx')
  132. else:
  133. self.send_error(404, 'Not Found')
  134. def handle_file_download(self, filename):
  135. try:
  136. with open(filename, 'rb') as f:
  137. self.send_response(200)
  138. self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  139. self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
  140. self.end_headers()
  141. self.wfile.write(f.read())
  142. except FileNotFoundError:
  143. self.send_error(404, 'File not found')
  144. class MyHandler(BaseHTTPRequestHandler):
  145. def do_GET(self):
  146. if self.path == 'документы/РП_Оперативные_оповещения_2_1_v1.docx':
  147. self.handle_file_download('РП_Оперативные_оповещения_2_1_v1.docx')
  148. else:
  149. self.send_error(404, 'Not Found')
  150. def handle_file_download(self, filename):
  151. try:
  152. with open(filename, 'rb') as f:
  153. self.send_response(200)
  154. self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  155. self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
  156. self.end_headers()
  157. self.wfile.write(f.read())
  158. except FileNotFoundError:
  159. self.send_error(404, 'File not found')
  160. class MyHandler(BaseHTTPRequestHandler):
  161. def do_GET(self):
  162. if self.path == 'документы/регион_РП_Сообщения_жителей_2_1_v1.docx':
  163. self.handle_file_download('регион_РП_Сообщения_жителей_2_1_v1.docx')
  164. else:
  165. self.send_error(404, 'Not Found')
  166. def handle_file_download(self, filename):
  167. try:
  168. with open(filename, 'rb') as f:
  169. self.send_response(200)
  170. self.send_header('Content-type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  171. self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
  172. self.end_headers()
  173. self.wfile.write(f.read())
  174. except FileNotFoundError:
  175. self.send_error(404, 'File not found')
  176. if __name__ == '__main__':
  177. # Создание глобального объекта сервера
  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('Сервер остановлен')