db de psql a sqlite
This commit is contained in:
parent
afdb6d231e
commit
2c94d656e5
44
db_conf.py
44
db_conf.py
@ -1,44 +0,0 @@
|
||||
import socket
|
||||
import psycopg2
|
||||
import json
|
||||
import os
|
||||
|
||||
ip_device = os.getenv("ip_device")
|
||||
db_server = json.loads(os.getenv("dist_servs"))[ip_device]
|
||||
|
||||
class DataBaseServer():
|
||||
db_server_ip = db_server
|
||||
port = 5432
|
||||
user = "postgres"
|
||||
|
||||
def get_data(self, query):
|
||||
conn = psycopg2.connect(
|
||||
host=DataBaseServer.db_server_ip,
|
||||
port=DataBaseServer.port,
|
||||
database="aldeas_inteligentes",
|
||||
user=DataBaseServer.user,
|
||||
password="Shala55951254"
|
||||
)
|
||||
cursor = conn.cursor()
|
||||
# Utiliza el parámetro 'query' que recibiste en el método
|
||||
cursor.execute(query)
|
||||
result = cursor.fetchall()
|
||||
cursor.close()
|
||||
conn.close()
|
||||
return result
|
||||
|
||||
def get_coordenadas(self):
|
||||
conn = psycopg2.connect(
|
||||
host=DataBaseServer.db_server_ip,
|
||||
port=DataBaseServer.port,
|
||||
database="coordenadas_mx",
|
||||
user="postgres",
|
||||
password="Shala55951254"
|
||||
)
|
||||
cursor = conn.cursor()
|
||||
# Utiliza el parámetro 'query' que recibiste en el método
|
||||
cursor.execute("SELECT* FROM coordenadas_mexico;")
|
||||
result = cursor.fetchall()
|
||||
cursor.close()
|
||||
conn.close()
|
||||
return result
|
86
help_files/01_create_database.py
Normal file
86
help_files/01_create_database.py
Normal file
@ -0,0 +1,86 @@
|
||||
import sqlite3
|
||||
import os
|
||||
import json
|
||||
# from tqdm import tqdm
|
||||
|
||||
db = "sict_csic.db"
|
||||
gen_path = lambda x : f'json_files/{x}'
|
||||
|
||||
# ################################################################
|
||||
# CREAR LA BASE DE DATOS
|
||||
# ################################################################
|
||||
|
||||
# Verificar si la base de datos existe y eliminarla
|
||||
if os.path.exists(db):
|
||||
os.remove(db)
|
||||
print("Base de datos existente eliminada.")
|
||||
|
||||
# Conectar a la base de datos (se crea si no existe)
|
||||
conexion = sqlite3.connect(db)
|
||||
cursor = conexion.cursor()
|
||||
|
||||
|
||||
# ################################################################
|
||||
# CREAR TABLA DE COORDENADAS
|
||||
# ################################################################
|
||||
|
||||
# Crear una tabla para almacenar JSON
|
||||
cursor.execute(
|
||||
'''
|
||||
CREATE TABLE IF NOT EXISTS coordenadas_mexico (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
json_data TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
# Leer el archivo JSON
|
||||
with open(gen_path('coordenas_unicas.json'), 'r', encoding='utf-8-sig') as f:
|
||||
json_coordenadas = json.load(f)
|
||||
|
||||
# Insertar el JSON en la tabla
|
||||
q_coordenadas = "INSERT INTO coordenadas_mexico (json_data) VALUES (?)"
|
||||
cursor.execute(q_coordenadas, (json.dumps(json_coordenadas),))
|
||||
|
||||
# ################################################################
|
||||
# CREAR TABLA DE DIR_CSIC
|
||||
# ################################################################
|
||||
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS dir_csict (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
json_data TEXT NOT NULL
|
||||
)
|
||||
''')
|
||||
|
||||
# Leer el archivo JSON
|
||||
with open(gen_path('DirectorioCSICT.json'), 'r', encoding='utf-8-sig') as f:
|
||||
json_dir_csic = json.load(f)
|
||||
|
||||
q_dir_csic = "INSERT INTO dir_csict (json_data) VALUES (?)"
|
||||
cursor.execute(q_dir_csic, (json.dumps(json_dir_csic),))
|
||||
|
||||
|
||||
# ################################################################
|
||||
# CREAR TABLA DE SITIOS
|
||||
# ################################################################
|
||||
|
||||
cursor.execute(
|
||||
'''
|
||||
CREATE TABLE sitios (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
json_data TEXT NOT NULL
|
||||
);
|
||||
''')
|
||||
|
||||
# Leer el archivo JSON
|
||||
with open(gen_path('sitios.json'), 'r', encoding='utf-8-sig') as f:
|
||||
json_sitios = json.load(f)
|
||||
|
||||
q_sitios = "INSERT INTO sitios (json_data) VALUES (?)"
|
||||
cursor.execute(q_sitios, (json.dumps(json_sitios),))
|
||||
|
||||
# Guardar cambios y cerrar conexión
|
||||
conexion.commit()
|
||||
conexion.close()
|
||||
print("base de datos creada exitosamente")
|
||||
|
21
help_files/db_cls.py
Normal file
21
help_files/db_cls.py
Normal file
@ -0,0 +1,21 @@
|
||||
import sqlite3
|
||||
|
||||
class DBSQLite():
|
||||
def __init__(self, db_name):
|
||||
self.db_name = db_name
|
||||
|
||||
def get_data(self, query, params=None):
|
||||
# Conectar a la base de datos y ejecutar una consulta
|
||||
if params is None:
|
||||
params = []
|
||||
|
||||
with sqlite3.connect(self.db_name) as conexion:
|
||||
cursor = conexion.cursor()
|
||||
cursor.execute(query, params) # Usa parámetros para evitar inyección SQL
|
||||
result = cursor.fetchall()
|
||||
return result
|
||||
|
||||
def get_coordenadas(self):
|
||||
# Obtener todas las coordenadas
|
||||
return self.get_data("SELECT * FROM coordenadas_mexico;")
|
||||
|
BIN
help_files/sict_csic.db
Normal file
BIN
help_files/sict_csic.db
Normal file
Binary file not shown.
@ -1,48 +0,0 @@
|
||||
import psycopg2
|
||||
import json
|
||||
import os
|
||||
|
||||
ip_device = os.getenv("ip_device")
|
||||
db_server = json.loads(os.getenv("dist_servs"))[ip_device]
|
||||
|
||||
f_path = os.path.join(os.getcwd(), "json_files/coordenas_unicas.json")
|
||||
|
||||
# cargar coordenadas a la memoria de la computadora
|
||||
# json_file_path = ".\json_files\coordenas_unicas.json"
|
||||
with open(f_path, 'r', encoding='utf-8-sig') as f:
|
||||
json_content = json.load(f)
|
||||
|
||||
# crear la conexión a la base de datos
|
||||
conn = psycopg2.connect(
|
||||
host=db_server,
|
||||
port=5432,
|
||||
database="coordenadas_mx",
|
||||
user="postgres",
|
||||
password="Shala55951254"
|
||||
)
|
||||
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("DROP TABLE IF EXISTS coordenadas_mexico;")
|
||||
|
||||
# crear la tabla en la base e datos
|
||||
create_table_query = """
|
||||
CREATE TABLE coordenadas_mexico (
|
||||
id SERIAL PRIMARY KEY,
|
||||
json_data JSONB
|
||||
);"""
|
||||
|
||||
cursor.execute(create_table_query)
|
||||
|
||||
# Insertar el contenido JSON en la tabla
|
||||
insert_query = "INSERT INTO coordenadas_mexico (json_data) VALUES (%s);"
|
||||
cursor.execute(insert_query, (json.dumps(json_content),))
|
||||
|
||||
# guardar cambios
|
||||
conn.commit()
|
||||
|
||||
# Cerrar la conexión
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
||||
print("se han cargado las coordenadas.")
|
@ -1,44 +0,0 @@
|
||||
import psycopg2
|
||||
import json
|
||||
import os
|
||||
|
||||
ip_device = os.getenv("ip_device")
|
||||
db_server = json.loads(os.getenv("dist_servs"))[ip_device]
|
||||
|
||||
# Parámetros de conexión a la base de datos
|
||||
file_path = os.path.join(os.getcwd(), "json_files/DirectorioCSICT.json")
|
||||
|
||||
# json_file_path = ".\json_files\DirectorioCSICT.json"
|
||||
with open(file_path, 'r', encoding='utf-8-sig') as f:
|
||||
json_content = json.load(f)
|
||||
|
||||
conn = psycopg2.connect(
|
||||
host=db_server,
|
||||
port=5432,
|
||||
database="aldeas_inteligentes",
|
||||
user="postgres",
|
||||
password="Shala55951254"
|
||||
)
|
||||
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("DROP TABLE IF EXISTS dir_csict;")
|
||||
|
||||
create_table_query = """
|
||||
CREATE TABLE dir_csict (
|
||||
id SERIAL PRIMARY KEY,
|
||||
json_data JSONB
|
||||
);"""
|
||||
|
||||
cursor.execute(create_table_query)
|
||||
|
||||
# Insertar el contenido JSON en la tabla
|
||||
insert_query = "INSERT INTO dir_csict (json_data) VALUES (%s);"
|
||||
cursor.execute(insert_query, (json.dumps(json_content),))
|
||||
|
||||
# guardar cambios
|
||||
conn.commit()
|
||||
# Cerrar la conexión
|
||||
cursor.close()
|
||||
conn.close()
|
||||
print(f'Servidor actualizado en directorio centros sict')
|
@ -1,44 +0,0 @@
|
||||
import psycopg2
|
||||
import json
|
||||
import os
|
||||
|
||||
ip_device = os.getenv("ip_device")
|
||||
db_server = json.loads(os.getenv("dist_servs"))[ip_device]
|
||||
|
||||
# Parámetros de conexión a la base de datos
|
||||
f_path = os.path.join(os.getcwd(), "json_files/sitios.json")
|
||||
|
||||
# json_file_path = ".\json_files\sitios.json"
|
||||
with open(f_path, 'r', encoding='utf-8-sig') as f:
|
||||
json_content = json.load(f)
|
||||
|
||||
conn = psycopg2.connect(
|
||||
host=db_server,
|
||||
port=5432,
|
||||
database="aldeas_inteligentes",
|
||||
user="postgres",
|
||||
password="Shala55951254"
|
||||
)
|
||||
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DROP TABLE IF EXISTS sitios;")
|
||||
|
||||
create_table_query = """
|
||||
CREATE TABLE sitios (
|
||||
id SERIAL PRIMARY KEY,
|
||||
json_data JSONB
|
||||
);"""
|
||||
|
||||
cursor.execute(create_table_query)
|
||||
|
||||
# Insertar el contenido JSON en la tabla
|
||||
insert_query = "INSERT INTO sitios (json_data) VALUES (%s);"
|
||||
cursor.execute(insert_query, (json.dumps(json_content),))
|
||||
|
||||
# guardar cambios
|
||||
conn.commit()
|
||||
|
||||
# Cerrar la conexión
|
||||
cursor.close()
|
||||
conn.close()
|
||||
print('Servidor actualizado en sitios')
|
0
log/access.log
Normal file
0
log/access.log
Normal file
0
log/error.log
Normal file
0
log/error.log
Normal file
36
main.py
36
main.py
@ -2,11 +2,14 @@ from flask import Flask, render_template, url_for, jsonify, send_file, send_from
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import StringField, PasswordField
|
||||
from wtforms.validators import DataRequired, InputRequired
|
||||
# from flask_cors import CORS
|
||||
import requests
|
||||
|
||||
import json
|
||||
import os
|
||||
from db_conf import *
|
||||
from help_files.db_cls import DBSQLite
|
||||
|
||||
db_path = os.path.join(os.getcwd(), "help_files/sict_csic.db")
|
||||
|
||||
DB = DBSQLite(db_path)
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['SECRET_KEY'] = 'SiCt2021CsIcDIX'
|
||||
@ -24,10 +27,14 @@ def home():
|
||||
user = form.username.data
|
||||
pswd = form.password.data
|
||||
|
||||
sitios = DataBaseServer().get_data('SELECT * FROM sitios;')[0][1]
|
||||
dirSubdirsEdos = DataBaseServer().get_data(
|
||||
'SELECT * FROM dir_csict;')[0][1]
|
||||
# print(dirSubdirsEdos)
|
||||
q_sitios = 'SELECT * FROM sitios;'
|
||||
sitios = DB.get_data(q_sitios)[0][1]
|
||||
sitios = json.loads(sitios)
|
||||
|
||||
q_dirSubdirsEdos = 'SELECT * FROM dir_csict;'
|
||||
dirSubdirsEdos = DB.get_data(q_dirSubdirsEdos)[0][1]
|
||||
dirSubdirsEdos = json.loads(dirSubdirsEdos)
|
||||
|
||||
for sitio in sitios:
|
||||
|
||||
gid = sitio['CodigoGid']
|
||||
@ -63,9 +70,6 @@ def home():
|
||||
return render_template('index.html', form=form)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@app.route('/mapa')
|
||||
def mapa():
|
||||
return render_template('mapa.html')
|
||||
@ -73,10 +77,10 @@ def mapa():
|
||||
|
||||
@app.route("/mapa/sitios_info")
|
||||
def sample():
|
||||
dataRequest = DataBaseServer().get_data('SELECT * FROM sitios;')[0][1]
|
||||
# with open("./database/sitios.json", mode="r", encoding="utf-8") as file:
|
||||
# dataRequest = json.load(file)
|
||||
|
||||
q_dataRequest = 'SELECT * FROM sitios;'
|
||||
dataRequest = DB.get_data(q_dataRequest)[0][1]
|
||||
dataRequest = json.loads(dataRequest)
|
||||
|
||||
lstSitios = []
|
||||
|
||||
for s in dataRequest:
|
||||
@ -92,7 +96,6 @@ def sample():
|
||||
'lenguasIndigenas': s['lenguasIndigenas'].title(),
|
||||
'fechaInstalacion': s['fechaInstalacion'],
|
||||
'infografiaSitio': s['infografiaSitio']
|
||||
|
||||
}
|
||||
lstSitios.append(tempObj)
|
||||
|
||||
@ -101,7 +104,8 @@ def sample():
|
||||
|
||||
@app.route('/mapa/coordenadas')
|
||||
def coordenadas():
|
||||
c = DataBaseServer().get_coordenadas()[0][1]
|
||||
c = DB.get_coordenadas()[0][1]
|
||||
c = json.loads(c)
|
||||
return jsonify(c)
|
||||
|
||||
|
||||
|
@ -1,18 +1,48 @@
|
||||
<VirtualHost *:80>
|
||||
ServerAdmin davidix1991@gmail.com
|
||||
ServerName sict-csic.page
|
||||
ServerAlias sict-csic.page
|
||||
DocumentRoot /var/www/sict_csic
|
||||
|
||||
WSGIDaemonProcess app user=www-data group=www-data threads=5 python-home=/var/www/sict_csic/.venv
|
||||
WSGIDaemonProcess app user=www-data group=www-data threads=4 python-home=/var/www/sict_csic/.venv
|
||||
WSGIScriptAlias / /var/www/sict_csic/sictApp.wsgi
|
||||
|
||||
ErrorLog /var/www/sict_csic/error_sict-csic.log
|
||||
CustomLog /var/www/sict_csic/access_sict-csic.log combined
|
||||
ErrorLog /var/www/sict_csic/log/error.log
|
||||
CustomLog /var/www/sict_csic/log/access.log combined
|
||||
|
||||
<Directory /var/www/sict_csic>
|
||||
WSGIProcessGroup app
|
||||
WSGIApplicationGroup %{GLOBAL}
|
||||
Order deny,allow
|
||||
# Order deny,allow
|
||||
Require all granted
|
||||
</Directory>
|
||||
</VirtualHost>
|
||||
|
||||
|
||||
# Habilitar caché para todas las solicitudes
|
||||
CacheEnable disk /
|
||||
|
||||
# Configuración de caché
|
||||
<IfModule mod_cache_disk.c>
|
||||
CacheRoot /var/cache/apache2/mod_cache_disk
|
||||
CacheDirLevels 2
|
||||
CacheDirLength 1
|
||||
# [bytes] Tamaño máximo de archivo a almacenar en caché
|
||||
CacheMaxFileSize 1000000
|
||||
# CacheMinFileSize bytes
|
||||
CacheMinFileSize 1
|
||||
CacheIgnoreHeaders Set-Cookie
|
||||
CacheIgnoreNoLastMod On
|
||||
|
||||
<FilesMatch "\.(jpg|jpeg|png|gif|css|js)$">
|
||||
# Indica si el caché está funcionando
|
||||
Header set X-Cache "HIT from Apache"
|
||||
# Expiración por defecto (1 hora)
|
||||
CacheDefaultExpire 3600
|
||||
# Expiración máxima (1 día)
|
||||
CacheMaxExpire 86400
|
||||
CacheLastModifiedFactor 0.5
|
||||
</FilesMatch>
|
||||
</IfModule>
|
||||
|
||||
</VirtualHost>
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user