-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
333 lines (298 loc) · 11.1 KB
/
server.py
File metadata and controls
333 lines (298 loc) · 11.1 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import json
import os
import urllib.parse
from jinja2 import Template
# Datos de prueba
countries = [
{ "codigo": 1, "nombre": "Colombia" },
{ "codigo": 2, "nombre": "Chile" },
{ "codigo": 3, "nombre": "Venezuela" },
{ "codigo": 4, "nombre": "Brasil" }
]
countries_dict = { c["codigo"]: c["nombre"] for c in countries }
cities = [
{ "codigo": 1, "nombre": "Cartagena", "codigo_pais": 1 },
{ "codigo": 2, "nombre": "Barranquilla", "codigo_pais": 1 },
{ "codigo": 3, "nombre": "Santa Marta", "codigo_pais": 1 },
{ "codigo": 4, "nombre": "Bogotá", "codigo_pais": 1 },
{ "codigo": 5, "nombre": "Medellín", "codigo_pais": 1 },
{ "codigo": 6, "nombre": "Santiago", "codigo_pais": 2 },
{ "codigo": 7, "nombre": "Valparaíso", "codigo_pais": 2 },
{ "codigo": 8, "nombre": "Concepción", "codigo_pais": 2 },
{ "codigo": 9, "nombre": "La Serena", "codigo_pais": 2 },
{ "codigo": 10, "nombre": "Antofagasta", "codigo_pais": 2 },
{ "codigo": 11, "nombre": "Caracas", "codigo_pais": 3 },
{ "codigo": 12, "nombre": "Maracaibo", "codigo_pais": 3 },
{ "codigo": 13, "nombre": "Valencia", "codigo_pais": 3 },
{ "codigo": 14, "nombre": "Barquisimeto", "codigo_pais": 3 },
{ "codigo": 15, "nombre": "Maturín", "codigo_pais": 3 },
{ "codigo": 16, "nombre": "Brasilia", "codigo_pais": 4 }
]
cities_dict = { c["codigo"]: c["nombre"] for c in cities }
sexo = [
{ "codigo": 1, "nombre": "Masculino" },
{ "codigo": 2, "nombre": "Femenino" }
]
sexo_dict = { c["codigo"]: c["nombre"] for c in sexo }
user = {
"username": "admin",
"password": "mauro",
"fullname": "Mauricio Hernandez"
}
# Base de datos de gestión
arrayBD = [
{
"names": "Juan Carlos",
"lastname": "Ramírez",
"email": "juan.ramirez@example.com",
"phone": "3001234567",
"pais": 1,
"ciudad": 10,
"addres": "Calle 123 #45-67",
"sexo": 1,
"fecha": "2024-03-15"
},
{
"names": "Laura",
"lastname": "Martínez",
"email": "laura.martinez@example.com",
"phone": "3109876543",
"pais": 1,
"ciudad": 11,
"addres": "Carrera 8 #12-34",
"sexo": 2,
"fecha": "2024-03-18"
},
{
"names": "Carlos Andrés",
"lastname": "Gómez",
"email": "carlos.gomez@example.com",
"phone": "3154567890",
"pais": 2,
"ciudad": 5,
"addres": "Av. Las Palmas 123",
"sexo": 1,
"fecha": "2024-04-01"
},
{
"names": "María Fernanda",
"lastname": "Rodríguez",
"email": "maria.rodriguez@example.com",
"phone": "3123456789",
"pais": 3,
"ciudad": 6,
"addres": "Cl 45 #10-11",
"sexo": 2,
"fecha": "2024-04-05"
},
{
"names": "Andrés Felipe",
"lastname": "Torres",
"email": "andres.torres@example.com",
"phone": "3112233445",
"pais": 1,
"ciudad": 8,
"addres": "Diagonal 77 #9-55",
"sexo": 1,
"fecha": "2024-03-25"
},
{
"names": "Paula Andrea",
"lastname": "López",
"email": "paula.lopez@example.com",
"phone": "3136677889",
"pais": 2,
"ciudad": 12,
"addres": "Calle 80 #15-22",
"sexo": 2,
"fecha": "2024-03-20"
},
{
"names": "Miguel Ángel",
"lastname": "Suárez",
"email": "miguel.suarez@example.com",
"phone": "3169998888",
"pais": 3,
"ciudad": 13,
"addres": "Av. Siempre Viva 742",
"sexo": 1,
"fecha": "2024-02-28"
},
{
"names": "Camila",
"lastname": "Moreno",
"email": "camila.moreno@example.com",
"phone": "3011122334",
"pais": 1,
"ciudad": 9,
"addres": "Transversal 23 #6-78",
"sexo": 2,
"fecha": "2024-04-02"
},
{
"names": "Sebastián",
"lastname": "Vargas",
"email": "sebastian.vargas@example.com",
"phone": "3145566778",
"pais": 2,
"ciudad": 4,
"addres": "Calle 100 #20-30",
"sexo": 1,
"fecha": "2024-03-10"
},
{
"names": "Valentina",
"lastname": "Castro",
"email": "valentina.castro@example.com",
"phone": "3171234567",
"pais": 1,
"ciudad": 7,
"addres": "Carrera 30 #55-66",
"sexo": 2,
"fecha": "2024-03-12"
}
]
class MiServidor(SimpleHTTPRequestHandler):
def do_GET(self):
# Rutas de la API
if self.path == "/countries":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(countries).encode("utf-8"))
return
elif self.path.startswith("/cities/id/"):
parts = self.path.split("/")
if len(parts) < 4 or not parts[3].isdigit():
self.send_error(400, "ID de país no válido")
return
codigo = int(parts[3])
data_city = [item for item in cities if item["codigo_pais"] == codigo]
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(data_city).encode("utf-8"))
return
elif self.path == "/sexos":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(sexo).encode("utf-8"))
return
# Servir archivos estáticos
if self.path == "/":
self.path = "/index.html"
elif self.path == "/login":
with open("login.html", "r", encoding="utf-8") as file:
html_template = file.read()
template = Template(html_template)
# respuesta
self.send_response(200) # 200 = Se completo proceso
self.send_header("Content-type","text/html")
self.end_headers()
self.wfile.write(template.render(error = "").encode("utf-8"))
elif self.path == "/admin":
self.path = "/admin.html"
elif self.path.startswith("/estilos/"):
self.path = "estilos/" + self.path[len("/estilos/"):]
elif self.path.startswith("/script/"):
self.path = "script/" + self.path[len("/script/"):]
elif self.path.startswith("/imagenes/"):
self.path = "imagenes/" + self.path[len("/imagenes/"):]
filepath = os.path.join(os.getcwd(), self.path.lstrip("/"))
if os.path.exists(filepath):
return SimpleHTTPRequestHandler.do_GET(self)
else:
self.send_error(404, "Archivo no encontrado")
def do_POST(self):
if self.path == "/send":
# Leer datos del formulario que envia
longitud = int(self.headers["Content-Length"])
recibe_datos = self.rfile.read(longitud).decode("utf-8")
datas = json.loads(recibe_datos) #urllib.parse.parse_qs(recibe_datos)
# Extraer los datos
arrayBD.append(
{
"names": datas["names"] ,
"lastname": datas["lastname"],
"email": datas["email"],
"phone": datas["phone"],
"pais": int(datas["pais"]),
"ciudad": int(datas["ciudad"]),
"addres": datas["addres"],
"sexo": int(datas["sexo"]),
"fecha": datas["fecha"],
})
# respuesta
self.send_response(200)
self.send_header("Location","/")
self.end_headers()
elif self.path == "/login":
# Leer datos del formulario que envia
longitud = int(self.headers["Content-Length"])
recibe_datos = self.rfile.read(longitud).decode("utf-8")
datas = urllib.parse.parse_qs(recibe_datos)
if datas["username"][0] == user["username"] and datas["password"][0] == user["password"]:
with open("admin.html", "r", encoding="utf-8") as file:
html_template = file.read()
template = Template(html_template)
# respuesta
self.send_response(200) # 200 = Se completo proceso
self.send_header("Content-type","text/html")
self.end_headers()
self.wfile.write(template.render(fullname = user["fullname"], arrayBD = arrayBD,countries = countries_dict, cities = cities_dict, sexo = sexo_dict ).encode("utf-8"))
else:
with open("login.html", "r", encoding="utf-8") as file:
html_template = file.read()
template = Template(html_template)
error_msg = "Usuario o Contraseña Incorrecta"
# respuesta
self.send_response(200) # 200 = Se completo proceso
self.send_header("Content-type","text/html")
self.end_headers()
self.wfile.write(template.render(error = error_msg).encode("utf-8"))
if self.path == "/update":
# Leer datos del formulario que envia
longitud = int(self.headers["Content-Length"])
recibe_datos = self.rfile.read(longitud).decode("utf-8")
datas = json.loads(recibe_datos) #urllib.parse.parse_qs(recibe_datos)
email = datas["email"]
i = 0
while i < len(arrayBD):
if email == arrayBD[i]["email"]:
arrayBD[i]["names"] = datas["names"]
arrayBD[i]["lastname"] = datas["lastname"]
arrayBD[i]["phone"] = datas["phone"]
arrayBD[i]["pais"] = int(datas["pais"])
arrayBD[i]["ciudad"] = int(datas["ciudad"])
arrayBD[i]["addres"] = datas["addres"]
arrayBD[i]["sexo"] = int(datas["sexo"])
arrayBD[i]["fecha"] = datas["fecha"]
break
i+=1
# respuesta
self.send_response(200)
self.send_header("Location","/")
self.end_headers()
def do_DELETE(self):
if self.path.startswith("/delete/email/"):
parts = self.path.split("/")
if len(parts) < 4:
self.send_error(400, "Email no valido")
return
email = parts[3]
i = 0
while i < len(arrayBD):
if email == arrayBD[i]["email"]:
del arrayBD[i]
break
i+=1
self.send_response(200)
self.end_headers()
response = {"status": "success", "message": "DELETED"}
self.wfile.write(json.dumps(response).encode("utf-8"))
# Iniciar el servidor
server = ThreadingHTTPServer(("localhost", 8080), MiServidor)
print("Servidor ejecutando en http://localhost:8080")
server.serve_forever()