generated from mariosky/WebRequestHandler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.py
120 lines (109 loc) · 4.82 KB
/
web.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qsl, urlparse
# Definición del contenido para diferentes rutas en el diccionario 'contenido'
contenido = {
'/': """
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ana Lee </title>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<h1>Ana Lee </h1>
<h2>Desarrolladora Web (Música/Diseño/Empresaria)</h2>
<h3>
¡Hola! Soy Ana Lee, una desarrolladora web que se especializa en la creación
de sitios web y aplicaciones web. Me encanta trabajar con tecnologías web modernas.
</h3>
<br />
<h2>Proyectos</h2>
<h3><a href="/proyecto/web-uno"> Web Estática - App de recomendación de libros </a></h3>
<h3><a href="/proyecto/web-dos"> Web App - MeFalta, que película o serie me falta ver </a></h3>
<h3><a href="/proyecto/web-tres"> Web App - Foto22, web para gestión de fotos </a></h3>
<br />
</body>
</html>
""",
'/proyecto/web-uno': """
<html>
<h1>Proyecto: Web Estática - App de recomendación de libros</h1>
<p>Este proyecto muestra una lista de libros recomendados basada en preferencias del usuario.</p>
</html>
""",
'/proyecto/web-dos': """
<html>
<h1>Proyecto: MeFalta</h1>
<p>Web App que te ayuda a recordar qué película o serie te falta ver.</p>
</html>
""",
'/proyecto/web-tres': """
<html>
<h1>Proyecto: Foto22</h1>
<p>Una web para gestionar y organizar tus fotos de manera eficiente.</p>
</html>
"""
}
# Función para leer archivos HTML desde el sistema de archivos
def leer_archivo_html(nombre_archivo):
# Esta función intenta leer un archivo HTML del sistema de archivos. Si el archivo no existe, devuelve un mensaje de error 404.
try:
with open(nombre_archivo, 'r', encoding="utf-8") as archivo:
return archivo.read()
except FileNotFoundError:
return "<h1>Error 404: Archivo no encontrado</h1>"
# Clase que maneja las solicitudes HTTP GET
class WebRequestHandler(BaseHTTPRequestHandler):
# Método para analizar la URL de la solicitud y obtener sus componentes
def url(self):
return urlparse(self.path)
# Método para convertir la cadena de consulta en un diccionario clave-valor
def query_data(self):
return dict(parse_qsl(self.url().query))
# Método para manejar solicitudes GET
def do_GET(self):
# Obtener la ruta solicitada
path = self.path
# Buscar en el diccionario el contenido correspondiente a la ruta
content = contenido.get(path, None)
# Si existe contenido para la ruta solicitada:
self.send_response(200) # Envía un código de respuesta HTTP 200 (OK)
self.send_header("Content-Type", "text/html") # Añade una cabecera que indica que el contenido es HTML
self.end_headers() # Finaliza el envío de cabeceras
self.wfile.write(self.get_response().encode("utf-8")) # Escribe y envía el contenido HTML codificado en UTF-8
# Método para manejar solicitudes GET
def do_POST(self):
# Obtener la ruta solicitada
path = self.path
# Buscar en el diccionario el contenido correspondiente a la ruta
content = contenido.get(path, None)
# Si existe contenido para la ruta solicitada:
self.send_response(200) # Envía un código de respuesta HTTP 200 (OK)
self.send_header("Content-Type", "text/html") # Añade una cabecera que indica que el contenido es HTML
self.end_headers() # Finaliza el envío de cabeceras
self.wfile.write(self.get_response().encode("utf-8")) # Escribe y envía el contenido HTML codificado en UTF-8
# Método adicional que no se utiliza actualmente, pero devuelve detalles de la solicitud
def get_response(self):
return f"""
<h1> Formulario </h1>
<form action="" method="post" class="forma-ejemplo">
<div class="forma">
<label for="nombre">Nombre:</label>
<input type="text" name="nombre" id="nombre" required/>
</div>
<div class="forma">
<label for="correo">Correo:</label>
<input type="correo" name="correo" id="correo" required/>
</div>
<div class="forma">
<input type="submit" vale="Registrate"/>
</div>
</form>
"""
# Inicialización del servidor
if __name__ == "__main__":
print("Starting server")
print("Puerto 8000")
server = HTTPServer(("0.0.0.0", 8000), WebRequestHandler) # Inicia el servidor en localhost en el puerto 8000
server.serve_forever() # Mantiene el servidor en ejecución de forma indefinida