Spaces:
				
			
			
	
			
			
		Sleeping
		
	
	
	
			
			
	
	
	
	
		
		
		Sleeping
		
	File size: 9,920 Bytes
			
			| e93cb8f | 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 | import streamlit as st
from PIL import Image
import pathlib
import platform
from BeautifulSoup import BeautifulSoup_st
from MechanicalSoup import MechanicalSoup_st
from pandas_html import df_html
from PostgreSQL import SQL
from Mysql import MySQL
from sql_lite import sqlite
st.write('''
        # DATABASES
        En esta DEMO me centré en desarrollar herramientas útiles para la extracción
        y almacenamiento de datos. Así, al inicio se introducen 3 bibliotecas
        que normalmente son utilizadas para la extracción de datos contenidos
        en páginas web y, al final, se presentan programas de SQL que más comúnmente
        son usados para el tratamiento y almacenamiento de datos.
        **Notas**:
        - Las bibliotecas de SQL se encuentran desarrolladas para trabajar con servidores
        remotos (con la excepción de SQLite).
        - El apartado de PostgreSQL se encuentra conectado remotamente a mi cuenta de Heroku.
        - El apartado de MySQL se encuentra conectado remotamente a mi cuenta de freesqldatabase.
        - El apartado de SQLite utiliza internamente un archivo de extensión .db como base de datos.
        - Si se desea trabajar los datos de manera local (localhost) se recomienda clonar el siguiente
         repositorio (https://github.com/raaraya1/Databases) y ejecutar la aplicación de streamlit
         desde la línea de comandos. (**recordar tener activados los servicios de postgresql o mysql según corresponda**)
        ''')
# methods to extract data from internet
st.write('''
## Web Scraping
''')
extract_choice = st.sidebar.selectbox('Web Scraping',
                    options=['BeautifulSoup',
                            'MechanicalSoup',
                            'Pandas (read_html)'])
if extract_choice == 'BeautifulSoup':
    navigation = BeautifulSoup_st()
    with st.expander('Cargar pagina web'):
        c1, c2 = st.columns([1, 2])
        c1.write('''### BeautifulSoup''')
        url = c2.text_input('URL')
    if url != '':
        navigation.load_page(f'{url}')
        with st.expander('Filtrar contenido'):
            navigation.filter_content()
        with st.expander('Guardar'):
            navigation.save()
elif extract_choice == 'MechanicalSoup':
    navigation = MechanicalSoup_st()
    with st.expander('Cargar pagina web'):
        c1, c2 = st.columns([1, 2])
        c1.write('''### MechanicalSoup''')
        url = c2.text_input('URL')
    if url != '':
        navigation.load_page(f'{url}')
        with st.expander('Filtrar contenido'):
            navigation.filter_content()
        with st.expander('Guardar'):
            navigation.save()
elif extract_choice == 'Pandas (read_html)':
    navigation = df_html()
    with st.expander('Cargar pagina web'):
        c1, c2 = st.columns([1, 2])
        c1.write('''### Pandas (read_html)''')
        url = c2.text_input('URL')
    if url != '':
        with st.expander('Tablas encontradas'):
            navigation.load_page(f'{url}')
        with st.expander('Guardar'):
            navigation.save()
# Methods to preproced data
st.write('''
## Structured Query Language (SQL)''')
work_choice = st.sidebar.selectbox('Structured Query Language (SQL)',
                                    options=['PostgreSQL',
                                    'MySQL',
                                    'SQLite'])
with st.expander('Conectar con una base de datos'):
    if work_choice == 'PostgreSQL':
        c1, c2 = st.columns([1, 1])
        img_logo = Image.open('img/PostgreSQL.png').resize((200, 200))
        c1.write('''#### PostgreSQL''')
        c1.image(img_logo)
        choice = st.radio('Conectar base de datos:', ['Externa', 'Interna'])
        if choice == 'Interna':
            database_name = st.secrets["postgres"]["dbname"]
            user_name = st.secrets["postgres"]["user"]
            password = st.secrets["postgres"]["password"]
            host = st.secrets["postgres"]["host"]
            port = st.secrets["postgres"]["port"]
            Postgre = SQL(database_name, user_name, password, host, port)
        elif choice == 'Externa':
            host = c2.text_input('Nombre del host')
            port = c2.text_input('Puerto')
            database_name = c2.text_input('Nombre de la base de datos')
            user_name = c2.text_input('Nombre de usuario')
            password = c2.text_input('Contraseña')
    elif work_choice == 'MySQL':
        c1, c2 = st.columns([1, 1])
        img_logo = Image.open('img/MySQL.png').resize((200, 200))
        c1.write('''#### MySQL''')
        c1.image(img_logo)
        choice = st.radio('Conectar base de datos:', ['Externa', 'Interna'])
        if choice == 'Interna':
            database_name = st.secrets["mysql"]["dbname"]
            user_name = st.secrets["mysql"]["user"]
            password = st.secrets["mysql"]["password"]
            host = st.secrets["mysql"]["host"]
            port = st.secrets["mysql"]["port"]
            Postgre = SQL(database_name, user_name, password, host, port)
        elif choice == 'Externa':
            host = c2.text_input('Nombre del host')
            port = c2.text_input('Puerto')
            database_name = c2.text_input('Nombre de la base de datos')
            user_name = c2.text_input('Nombre de usuario')
            password = c2.text_input('Contraseña')
    elif work_choice == 'SQLite':
        c1, c2 = st.columns([1, 3])
        img_logo = Image.open('img/SQLite.png').resize((160, 100))
        c1.image(img_logo)
        choice = st.radio('Conectar base de datos:', ['Externa', 'Interna'])
        database_path = None
        if choice == 'Interna': database_path = 'database.db'
if work_choice == 'PostgreSQL':
    if database_name != '' and user_name != '' and password != '' and host != '' and port != '':
        Postgre = SQL(database_name, user_name, password, host, port)
        with st.expander('Tablas cargadas'):
            c1, c2, c3, c4 = st.columns([2, 1, 1, 1])
            mostrar_tablas = c1.checkbox('Mostrar tablas', key='mostrar')
            Importar_tabla = c2.checkbox('Importar tabla', key='importar')
            Eliminar_tabla = c2.checkbox('Eliminar tabla', key='eliminar')
            Primary_key = c3.checkbox('Primary Key', key='primary_key')
            Foreign_Key = c3.checkbox('Foreign Key', key='foreign_key')
            Change_type = c4.checkbox('Tipo columna', key='type_col')
            c1, c2 = st.columns(2)
            with c1.container():
                if mostrar_tablas: Postgre.todas_las_tablas()
            with c2.container():
                if Importar_tabla: Postgre.importar_tabla()
                elif Eliminar_tabla: Postgre.eliminar_tabla()
                elif Primary_key: Postgre.primary_key_st()
                elif Change_type: Postgre.change_datatype_st()
            if Foreign_Key: Postgre.foreign_key_st()
        with st.expander('Ejecutar un comando'):
            comand = str(st.text_area('Comando de SQL'))
            if comand != '': Postgre.mostrar_tabla(comand)
elif work_choice == 'MySQL':
    if database_name != '' and user_name != '' and password != '' and host != '' and port != '':
        mysql = MySQL(database_name, user_name, password, host, port)
        with st.expander('Tablas cargadas'):
            c1, c2, c3, c4 = st.columns([2, 1, 1, 1])
            mostrar_tablas = c1.checkbox('Mostrar tablas', key='mostrar')
            Importar_tabla = c2.checkbox('Importar tabla', key='importar')
            Eliminar_tabla = c2.checkbox('Eliminar tabla', key='eliminar')
            Primary_key = c3.checkbox('Primary Key', key='primary_key')
            Foreign_Key = c3.checkbox('Foreign Key', key='foreign_key')
            Change_type = c4.checkbox('Tipo columna', key='type_col')
            c1, c2 = st.columns(2)
            with c1.container():
                if mostrar_tablas: mysql.todas_las_tablas()
            with c2.container():
                if Importar_tabla: mysql.importar_tabla()
                elif Eliminar_tabla: mysql.eliminar_tabla()
                elif Primary_key: mysql.primary_key_st()
                elif Change_type: mysql.change_datatype_st()
            if Foreign_Key: mysql.foreign_key_st()
        with st.expander('Ejecutar un comando'):
            comand = str(st.text_area('Comando de SQL'))
            if comand != '': mysql.mostrar_tabla(comand)
elif work_choice == 'SQLite':
# NOTA:
# sqlite no deja modificar las tablas, por eso lo que hay que hacer es
# copiar la info, crear una nueva tabla (con las modificaciones) y luego hacer los
# cambios. Esto metodo lo voy a hacer para establecer las primary key y las
# Foreign keys
    if database_path != '':
        SQLITE = sqlite(database_path)
        with st.expander('Tablas cargadas'):
            c1, c2, c3, c4 = st.columns([2, 1, 1, 1])
            mostrar_tablas = c1.checkbox('Mostrar tablas', key='mostrar')
            Importar_tabla = c2.checkbox('Importar tabla', key='importar')
            Eliminar_tabla = c2.checkbox('Eliminar tabla', key='eliminar')
            Primary_key = c3.checkbox('Primary Key', key='primary_key')
            Foreign_Key = c3.checkbox('Foreign Key', key='foreign_key')
            Change_type = c4.checkbox('Tipo columna', key='type_col')
            c1, c2 = st.columns(2)
            with c1.container():
                if mostrar_tablas: SQLITE.todas_las_tablas()
            with c2.container():
                if Importar_tabla: SQLITE.importar_tabla()
                elif Eliminar_tabla: SQLITE.eliminar_tabla()
                elif Primary_key: SQLITE.primary_key_st()
                elif Change_type: SQLITE.change_datatype_st()
            if Foreign_Key: SQLITE.foreign_key_st()
        with st.expander('Ejecutar un comando'):
            comand = str(st.text_area('Comando de SQL'))
            if comand != '': SQLITE.mostrar_tabla(comand)
 |