Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import http.server
- import socketserver
- import os
- import json
- # NOTA: O módulo 'cgi' não é mais necessário com esta abordagem.
- # --- Configurações do Servidor ---
- PORT = 5000
- UPLOAD_DIR = 'uploads'
- # --- Variável Global ---
- flash_command = 'FLASH_OFF'
- # Garante que o diretório de uploads existe.
- if not os.path.exists(UPLOAD_DIR):
- os.makedirs(UPLOAD_DIR)
- class MyHttpRequestHandler(http.server.BaseHTTPRequestHandler):
- def write_response(self, data):
- try:
- self.wfile.write(data)
- except BrokenPipeError:
- print("AVISO: BrokenPipeError - Cliente desconectou.")
- def do_GET(self):
- # As rotas GET permanecem as mesmas
- if self.path == '/':
- self.send_response(200)
- self.send_header('Content-type', 'text/html')
- self.end_headers()
- with open('index3.html', 'rb') as f:
- self.write_response(f.read())
- elif self.path.startswith('/latest-photo'):
- photo_path = os.path.join(UPLOAD_DIR, 'latest.jpg')
- if os.path.exists(photo_path):
- self.send_response(200)
- self.send_header('Content-type', 'image/jpeg')
- self.end_headers()
- with open(photo_path, 'rb') as f:
- self.write_response(f.read())
- else:
- self.send_error(404, 'Foto não encontrada.')
- elif self.path == '/command':
- self.send_response(200)
- self.send_header('Content-type', 'text/plain')
- self.end_headers()
- self.write_response(flash_command.encode('utf-8'))
- else:
- self.send_error(404, 'Página não encontrada.')
- def do_POST(self):
- global flash_command
- try:
- # --- NOVA ROTA PARA UPLOAD DIRETO (RAW) ---
- if self.path == '/raw_upload':
- content_length = int(self.headers['Content-Length'])
- # Lê exatamente o número de bytes especificado no cabeçalho
- image_data = self.rfile.read(content_length)
- # Verifica se a quantidade de dados recebida é a esperada
- if len(image_data) == content_length:
- file_path = os.path.join(UPLOAD_DIR, 'latest.jpg')
- with open(file_path, 'wb') as f:
- f.write(image_data)
- print(f"SUCESSO (RAW): Foto recebida ({len(image_data)} bytes) e salva.")
- self.send_response(200)
- self.send_header('Content-type', 'application/json')
- self.end_headers()
- response = {'status': 'success', 'message': 'Upload raw bem-sucedido!'}
- self.write_response(json.dumps(response).encode('utf-8'))
- else:
- print(f"ERRO: Upload incompleto. Esperado: {content_length}, Recebido: {len(image_data)}")
- self.send_error(400, 'Upload incompleto.')
- # A rota de comando continua a mesma
- elif self.path == '/command':
- content_length = int(self.headers['Content-Length'])
- post_data = self.rfile.read(content_length)
- data = json.loads(post_data.decode('utf-8'))
- command = data.get('command')
- if command in ['FLASH_ON', 'FLASH_OFF']:
- flash_command = command
- self.send_response(200)
- self.send_header('Content-type', 'application/json')
- self.end_headers()
- response = {'message': 'Comando atualizado!', 'newCommand': flash_command}
- self.write_response(json.dumps(response).encode('utf-8'))
- else:
- self.send_error(400, 'Comando invalido.')
- except Exception as e:
- print(f"ERRO INESPERADO no POST: {e}")
- self.send_error(500, 'Erro interno do servidor')
- if __name__ == "__main__":
- with socketserver.TCPServer(("", PORT), MyHttpRequestHandler) as httpd:
- print(f"Servidor Python (com Upload RAW) rodando na porta {PORT}")
- httpd.serve_forever()
Add Comment
Please, Sign In to add comment