I am trying to access a database made in Access with a backend in python with the pyodbc library, but the page reloads repeatedly.
When I open the page in localhost for the first time, it works fine, and if I look at the web console I can see the data from my database. But then if I reload the web the page starts to reload uncontrollably, without stopping. Network events start to accumulate with names test.html
, siolated-first.jst
, test.js
, contacts
and ws
, one after another without stopping. In the console for a moment the data can be seen briefly but the page reloads immediately. That is, the web page once it is loaded with f5, starts to refresh in the same way without stopping, as if you were pressing f5 without stopping.
Another thing is that in my code I don’t use ws either in front or backend.
let isDataLoaded = false; // Evita que el fetch se ejecute varias veces
function loadContacts() {
if (isDataLoaded) {
console.log("Ya se cargaron los contactos, no se ejecuta fetch nuevamente.");
return;
}
isDataLoaded = true; // Se establece que ya se ha cargado
console.log("Realizando fetch para cargar contactos.");
let url = "http://localhost:8000/contactos";
fetch(url)
.then(response => response.json())
.then(data => {
console.log("Datos obtenidos:", data);
})
.catch(error => console.log("Error al obtener contactos:", error));
}
document.addEventListener("DOMContentLoaded", loadContacts);
import json
import pyodbc
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_PATH = os.path.join(BASE_DIR, 'contactsDB.mdb')
CONNECTION_STRING = f'DRIVER={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={DB_PATH};'
def get_connection():
return pyodbc.connect(CONNECTION_STRING)
class ContactHandler(BaseHTTPRequestHandler):
def _set_headers(self):
"""Establece los encabezados CORS y de respuesta"""
self.send_header('Content-Type', 'application/json')
# Permite solicitudes desde cualquier origen (o puedes poner tu origen específico)
self.send_header('Access-Control-Allow-Origin', '*') # o '*' para todos los orígenes
self.send_header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
self.send_header('Cache-Control', 'no-store') # Evita cache en cliente
self.end_headers()
def do_OPTIONS(self):
"""Manejo de las solicitudes pre-flight de CORS"""
self.send_response(200)
self._set_headers()
self.wfile.write(b'') # Respuesta vacía para la solicitud OPTIONS
def do_GET(self):
if self.path == '/contactos':
try:
print("Recibiendo solicitud GET para /contactos") # Agrega un log
conn = get_connection()
cursor = conn.cursor()
cursor.execute('SELECT * FROM contacts ORDER BY nombre')
rows = cursor.fetchall()
conn.close()
contactos = [{'nombre': row.nombre, 'telefono': row.telefono, 'edad': row.edad} for row in rows]
print(f"Enviando contactos: {contactos}") # Log de lo que se envía
self.send_response(200)
self._set_headers()
self.wfile.write(json.dumps(contactos).encode('utf-8'))
except Exception as e:
self.send_response(500)
self._set_headers()
self.wfile.write(json.dumps({'error': str(e)}).encode('utf-8'))
print(f"Error: {e}")
def do_POST(self):
if self.path == '/contactos':
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data)
nombre = data.get('nombre')
telefono = data.get('telefono')
edad = data.get('edad')
try:
conn = get_connection()
cursor = conn.cursor()
cursor.execute('INSERT INTO contacts (nombre, telefono, edad) VALUES (?, ?, ?)', (nombre, telefono,edad))
conn.commit()
conn.close()
self.send_response(201)
self._set_headers()
self.wfile.write(json.dumps({'message':'contacto agregado'}).encode('utf-8'))
except Exception as e:
self.send_response(500)
self._set_headers()
self.wfile.write(json.dumps({'error':str(e)}).encode('utf-8'))
def do_DELETE(self):
if self.path.startswith('/contactos'):
nombre= self.path.split('/')[-1]
try:
conn = get_connection()
cursor = conn.cursor()
cursor.execute('DELETE FROM contacts WHERE nombre = ?', (nombre,))
conn.commit()
conn.close()
self.send_response(200)
self._set_headers()
self.wfile.write(json.dumps({'message': 'contacto eliminado'}).encode('utf-8'))
except Exception as e:
self.send_response(500)
self._set_headers()
self.wfile.write(json.dumps({'error':str(e)}).encode('utf-8'))
def run_server():
server_address = ('', 8000)
httpd = HTTPServer(server_address, ContactHandler)
print("servidor corriendo en http://localhost:8000")
httpd.serve_forever()
if __name__ == '__main__':
run_server()
What should happen is that the query is generated only once, and not that it starts to repeat itself indefinitely as it happens.