Propósito: es una libraría permite la creación de Dashboard interactivos.
Es un framework de aplicación de código abierto (un paquete de Python) que nos
brinda el poder de crear aplicaciones atractivas sin ningún conocimiento de
desarrollo de front-end.
Esto nos libera de involucrarnos en cualquier marco de trabajo front-end o codificación
en HTML, CSS y JavaScript.
Utiliza Python puro para desarrollar su front-end.
En primer lugar, si está codificando secuencias de comandos de Python que se ejecutan
regularmente en una máquina con un programador de trabajos como cron, Streamlit no es útil
para usted.
Pero si está desarrollando una herramienta que desea compartir con los miembros de su equipo,
por ejemplo, una aplicación de investigación de palabras clave, puede usar Streamlit.
Además, si necesita un método de autenticación de usuario, la comunidad Streamlit desarrolló
un paquete que puede manejarlo por usted.
Para instalar el paquete streamlit ejecute el siguiente comando, el cual
a continuación se presentan el correspondiente comando de tu sistema operativo:
$ pip install streamlit
> pip install streamlit
Puede probar si la instalación se realizo correctamente, ejecutando
el siguiente comando correspondiente a tu sistema operativo:
A continuación se presenta la ejecución de una demostración que incluye Streamlit,
ejecutando el siguiente comando correspondiente a tu sistema operativo:
$ streamlit hello
> streamlit hello
El anterior comando al ejecutar debe mostrar el siguiente mensaje:
Welcome to Streamlit. Check out our demo in your browser.Local URL: http://localhost:8501Network URL: http://172.28.94.109:8501Ready to create your own Python apps super quickly?Head over to https://docs.streamlit.ioMay you create awesome apps!
LocalURL
Dirección local de tu PC donde ejecuta esta demostración, valor por
defecto es http://localhost:8501
NetworkURL
Dirección de la red local de tu PC donde donde puede compartir la forma
como accede a esta demostración.
Abra el navegador web en la dirección local definida en el valor LocalURL:
Esta aplicación muestra cómo puede usar Streamlit para crear animaciones
geniales. Muestra un fractal animado basado en el conjunto de Julia. Utilice
el control deslizante para ajustar diferentes parámetros.
Esta demostración ilustra una combinación de Plotting y animación con Streamlit.
En este ejemplo se genera un montón de números aleatorios en un bucle durante
unos 5 segundos.
Esta demostración muestra cómo usar st.pydeck_chart para mostrar datos geoespaciales.
Esta demostración muestra cómo usar st.write para visualizar Pandas DataFrames.
(Datos cortesía de UN Data Explorer).
A continuación se presenta la ejecución de una demostración personalizada de Hello World,
ejecutando los siguientes comandos correspondiente a tu sistema operativo:
$ pip install -r hello_word/requirements.txt
$ streamlit run hello_word/app.py
> pip install -r hello_word/requirements.txt> streamlit run hello_word/app.py
El anterior comando al ejecutar debe mostrar el siguiente mensaje:
You can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://172.28.94.109:8501
LocalURL
Dirección local de tu PC donde ejecuta esta demostración, valor por
defecto es http://localhost:8501
NetworkURL
Dirección de la red local de tu PC donde donde puede compartir la forma
como accede a esta demostración.
Abra el navegador web en la dirección local definida en el valor LocalURL:
De esta forma tiene una práctica real de crear un mensaje Hello World y usado la
librería Streamlit.
A continuación se presenta una práctica de un Dashboard de análisis de ventas de
tres (03) sucursales a nivel nacional de una cadena de supermercado usando
con Streamlit, a continuación la estructura de proyecto llamado dashboard:
# @Email: leonardocaballero@gmail.com# @Website: https://entrenamiento-data-scientist-python.readthedocs.io/# @Github: https://github.com/macagua# @Project: Tablero de Ventas con Streamlitimportosimportpandasaspdimportplotly.expressaspximportstreamlitasstFULL_PATH=(os.path.dirname(os.path.abspath(__file__))+os.sep+"ventas_supermercado.xlsx")# emojis: https://www.webfx.com/tools/emoji-cheat-sheet/st.set_page_config(page_title="Tablero de Ventas",page_icon=":bar_chart:",layout="wide")# ---- LEER ARCHIVO EXCEL ----@st.cachedefget_data_from_excel():df=pd.read_excel(io=FULL_PATH,engine="openpyxl",sheet_name="Ventas",skiprows=3,usecols="B:R",nrows=1000,)# Agregar columna 'hour' al dataframedf["hour"]=pd.to_datetime(df["Time"],format="%H:%M:%S").dt.hourdf.rename(columns={"hour":"Hora"},inplace=True)returndfdf=get_data_from_excel()# ---- BARRA LATERAL ----st.sidebar.header("Por favor, filtre aquí:")ciudad=st.sidebar.multiselect("Seleccione la Ciudad:",options=df["Ciudad"].unique(),default=df["Ciudad"].unique(),)tipo_cliente=st.sidebar.multiselect("Seleccione el tipo de Cliente:",options=df["Tipo_Cliente"].unique(),default=df["Tipo_Cliente"].unique(),)genero=st.sidebar.multiselect("Seleccione el Genero:",options=df["Genero"].unique(),default=df["Genero"].unique(),)df_seleccion=df.query("Ciudad == @ciudad & Tipo_Cliente ==@tipo_cliente & Genero == @genero")df_seleccion.rename(columns={"Linea producto":"Línea de producto"},inplace=True)# ---- PAGINA PRINCIPAL ----st.title(":bar_chart: Tablero de Ventas")st.markdown("##")# KPI PRINCIPALEStotal_ventas=int(df_seleccion["Total"].sum(numeric_only=True))puntuacion_media=round(df_seleccion["Clasificacion"].mean(),1)puntuacion_star=":star:"*int(round(puntuacion_media,0))ventas_promedio_por_transaccion=round(df_seleccion["Total"].mean(),2)columna_izquierda,columna_media,columna_derecha=st.columns(3)withcolumna_izquierda:st.subheader("Total de Ventas:")st.subheader(f"Bs. {total_ventas:,}")withcolumna_media:st.subheader("Puntuación media:")st.subheader(f"{puntuacion_media}{puntuacion_star}")withcolumna_derecha:st.subheader("Ventas promedio por transacción:")st.subheader(f"Bs. {ventas_promedio_por_transaccion}")st.markdown("""---""")# VENTAS POR LÍNEA DE PRODUCTO [GRÁFICO DE BARRAS]ventas_por_linea_producto=(df_seleccion.groupby(by=["Línea de producto"]).sum(numeric_only=True)[["Total"]].sort_values(by="Total"))fig_ventas_producto=px.bar(ventas_por_linea_producto,x="Total",y=ventas_por_linea_producto.index,orientation="h",title="<b>Ventas por Línea de Producto</b>",color_discrete_sequence=["#0083B8"]*len(ventas_por_linea_producto),template="plotly_white",)fig_ventas_producto.update_layout(plot_bgcolor="rgba(0,0,0,0)",xaxis=(dict(showgrid=False)))# VENTAS POR HORA [GRÁFICO DE BARRAS]ventas_por_horas=df_seleccion.groupby(by=["Hora"]).sum(numeric_only=True)[["Total"]]fig_ventas_por_horas=px.bar(ventas_por_horas,x=ventas_por_horas.index,y="Total",title="<b>Ventas por hora</b>",color_discrete_sequence=["#0083B8"]*len(ventas_por_horas),template="plotly_white",)fig_ventas_por_horas.update_layout(xaxis=dict(tickmode="linear"),plot_bgcolor="rgba(0,0,0,0)",yaxis=(dict(showgrid=False)),)columna_izquierda,columna_derecha=st.columns(2)columna_izquierda.plotly_chart(fig_ventas_por_horas,use_container_width=True)columna_derecha.plotly_chart(fig_ventas_producto,use_container_width=True)# ---- HIDE STREAMLIT STYLE ----hide_st_style=""" <style> #MainMenu {visibility: hidden;} footer {visibility: hidden;} header {visibility: hidden;} </style> """st.markdown(hide_st_style,unsafe_allow_html=True)
Archivo .streamlit/config.toml
Archivo de configuración de proyecto Streamlit.
1 2 3 4 5 6 7 8 910111213141516
[theme]# Primary accent color for interactive elements.primaryColor="#E694FF"# Background color for the main content area.backgroundColor="#00172B"# Background color used for the sidebar and most interactive widgets.secondaryBackgroundColor="#0083B8"# Color used for almost all text.textColor="#FFF"# Font family for all text in the app, except code blocks. One of "sans serif", "serif", or "monospace".# Default: "sans serif"font="sans serif"
Archivo de la hoja de calculo de MicrosoftExcel llamado ventas_supermercado.xlsx
la cual no se incluye ya que cada vez que se inicia el programa app.py, para cuidar la
creación de los datos iniciales.
A continuación se presenta la ejecución de una demostración personalizada de TablerodeVentas,
ejecutando los siguientes comandos correspondiente a tu sistema operativo:
$ pip install -r dashboard/requirements.txt
$ streamlit run dashboard/app.py
> pip install -r dashboard/requirements.txt> streamlit run dashboard/app.py
El anterior comando al ejecutar debe mostrar el siguiente mensaje:
You can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://172.28.94.109:8501
LocalURL
Dirección local de tu PC donde ejecuta esta demostración, valor por
defecto es http://localhost:8501
NetworkURL
Dirección de la red local de tu PC donde donde puede compartir la forma
como accede a esta demostración.
Abra el navegador web en la dirección local definida en el valor LocalURL:
De esta forma tiene una práctica real de crear un Tablero de Ventas, usando fuente
de datos desde una hoja de calculo de Excel y usado la librería Streamlit.
A continuación se presenta una práctica de un simple Blog que hace las operaciones
de manipulación CRUD para generar analítica de las entradas del Blog con Streamlit,
a continuación la estructura de proyecto llamado sqlite_crud:
importdatetimeimportloggingimportmatplotlibaspltimportosimportpandasaspdimportsqlite3importstreamlitasstfromdbimportcreate_connectionfromlayoutsimport(BLOG_HEADER_HTML_TPL,ENTRY_DETAILS_HTML_TPL,ENTRY_CONTENT_MSG_HTML_TPL,HOME_ENTRIES_HTML_TPL,NOTFOUND_ENTRY_MSG_HTML_TPL,NOTFOUND_SEARCH_MSG_HTML_TPL,)fromsettingsimport(APP_TITLE,PRIMARY_COLOR,BACKGROUND_COLOR,SECONDARY_BACKGROUND_COLOR,TEXT_COLOR,DB,INSERT_SQL_SCRIPTS,SELECT_DISTINCT_SQL_SCRIPTS,SELECT_SQL_SCRIPTS,)fromstreamlit_quillimportst_quillfromwordcloudimportWordCloud# Logging Applogging.basicConfig(level=logging.INFO)# Streamlitst.set_option('deprecation.showPyplotGlobalUse',False)st.set_page_config(page_title=APP_TITLE,page_icon=":page_facing_up:",layout="wide")st.markdown('''<style type="text/css"> #MainMenu{visibility: hidden;} footer{visibility: hidden;} /*#root>div:nth-child(1)>div>div>div>div>section>div{padding-top: 0rem;}*/ </style>''',unsafe_allow_html=True)# Functionsdefadd_data(db_connection,sql_script,author,title,content,postdate):"""Add a Blog entry Args: db_connection (Connection): SQLite database connection representation sql_script (str): SQL script to execute author (str): The Article author title (str): The Article title content (str): The Article body postdate (datetime): The Article post date """try:cursor=db_connection.cursor()cursor.execute(sql_script,(author,title,content,postdate),)db_connection.commit()logging.info("¡{} record(s) was(were) successfully added to the table!".format(cursor.rowcount))exceptsqlite3.Erroraserror:logging.error(f"Query for record(s) in table failed! {error}")finally:ifcursor:cursor.close()logging.info("The cursor for add a Blog entry was closed successfully!")defview_all_articles(db_connection,sql_script):"""View all Blog Articles Args: db_connection (Connection): SQLite database connection representation sql_script (str): SQL script to execute Returns: list: Records list """records=[]try:cursor=db_connection.cursor()cursor.execute(sql_script)records=cursor.fetchall()logging.info("The query to the table was successful!")exceptsqlite3.Erroraserror:logging.error(f"Query for record(s) in table failed! {error}")finally:ifcursor:cursor.close()logging.info("The cursor for view all Blog articles was closed successfully!")returnrecordsdefview_all_article_titles(db_connection,sql_script):"""View all Titles Blog Articles Args: db_connection (Connection): SQLite database connection representation sql_script (str): SQL script to execute Returns: list: Records list """records=[]try:cursor=db_connection.cursor()cursor.execute(sql_script)records=cursor.fetchall()logging.info("The query to the table was successful!")exceptsqlite3.Erroraserror:logging.error(f"Query for record(s) in table failed! {error}")finally:ifcursor:cursor.close()logging.info("The cursor for view all titles Blog articles was closed successfully!")returnrecordsdefget_blog_by_title(db_connection,title):"""Get the title of Blog article Args: db_connection (Connection): SQLite database connection representation title (str): The Article title Returns: list: Records list """records=[]try:cursor=db_connection.cursor()cursor.execute(f'SELECT * FROM articles WHERE title="{title}"')records=cursor.fetchall()logging.info("The query to the table by title was successful!")exceptsqlite3.Erroraserror:logging.error(f"Query for record(s) in table failed! {error}")finally:ifcursor:cursor.close()logging.info("The cursor for get the title of Blog article was closed successfully!")returnrecordsdefget_blog_by_author(db_connection,author):"""Get all Blog articles by author Args: db_connection (Connection): SQLite database connection representation author (str): The Article author Returns: list: Records list """records=[]try:cursor=db_connection.cursor()cursor.execute(f'SELECT * FROM articles WHERE author="{author}"')records=cursor.fetchall()logging.info("The query to the table by author was successful!")exceptsqlite3.Erroraserror:logging.error(f"Query for record(s) in table failed! {error}")finally:ifcursor:cursor.close()logging.info("The cursor for get all Blog articles by author was closed successfully!")returnrecords# def update_data(db_connection, author, title, content, postdate):# """Update the Blog article# Args:# db_connection (Connection): SQLite database connection representation# author (str): The Article author# title (str): The Article title# content (str): The Article body# postdate (datetime): The Article post date# """# passdefdelete_data(db_connection,title):"""Delete the Blog article Args: db_connection (Connection): SQLite database connection representation title (str): The Article title """try:cursor=db_connection.cursor()cursor.execute(f'DELETE FROM articles WHERE title="{title}"')db_connection.commit()logging.info("The selected record was successfully deleted!")exceptsqlite3.Erroraserror:logging.error(f"Delete record(s) in table failed! {error}")finally:ifcursor:cursor.close()logging.info("The cursor for delete the blog article was closed successfully!")defrender_about(*_)->None:"""Show App info """st.write("""\# Streamlit App Demo - {app_title}Howdy :wave:!Welcome to my Streamlit Full Stack App exploration.This started as the {app_title} Fullstack App with just Streamlit + SQLite.""".format(app_title=APP_TITLE))defmain(db_connection):"""A Simple CRUD Blog Args: db_connection (Connection): SQLite database connection representation """st.markdown(BLOG_HEADER_HTML_TPL.format(div_bg_color=SECONDARY_BACKGROUND_COLOR,h1_color=TEXT_COLOR,app_title=APP_TITLE),unsafe_allow_html=True)menu=["Home","View Posts","Add Posts",# "Update Posts","Search...","Manage Blog","About"]choice=st.sidebar.selectbox("Menu",menu,help="Select a choice from the select list!")ifchoice=="Home":st.subheader("Home")result=view_all_articles(db_connection,SELECT_SQL_SCRIPTS)iflen(result)==0:st.markdown(NOTFOUND_ENTRY_MSG_HTML_TPL,unsafe_allow_html=True)else:forarticleinresult:post_author=article[0]post_title=article[1]post_content=str(article[2])[0:90]post_date=article[3]st.markdown(HOME_ENTRIES_HTML_TPL.format(div_bg_color=PRIMARY_COLOR,title=post_title,author=post_author,date=post_date,content=post_content),unsafe_allow_html=True,)elifchoice=="View Posts":st.subheader("View Articles")all_titles=[article[0]forarticleinview_all_article_titles(db_connection,SELECT_DISTINCT_SQL_SCRIPTS)]post_list=st.sidebar.selectbox("View Posts",all_titles,help="Select a choice from the select list!")post_result=get_blog_by_title(db_connection,post_list)iflen(all_titles)==0:st.markdown(NOTFOUND_ENTRY_MSG_HTML_TPL,unsafe_allow_html=True)else:forarticleinpost_result:post_author=article[0]post_title=article[1]post_content=article[2]post_date=article[3]# st.text(f"Reading Time:{readingTime(post_content)}")st.markdown(ENTRY_DETAILS_HTML_TPL.format(div_bg_color=PRIMARY_COLOR,title=post_title,author=post_author,date=post_date),unsafe_allow_html=True,)st.markdown(ENTRY_CONTENT_MSG_HTML_TPL.format(content=post_content),unsafe_allow_html=True)elifchoice=="Add Posts":st.subheader("Add Articles")blog_author=st.text_input(label="Enter Author Name",help="Please, enter the Author Name",placeholder="Example, Leonardo Caballero",max_chars=50)blog_title=st.text_input(label="Enter Post Title",help="Please, enter the Post Title",placeholder="Example, Data science for Python",)blog_content=st_quill(#value='',placeholder='Example, Python is very great option for Data science today!',html=True,)blog_post_date=st.date_input(label="Pick publication date",help="Please, pick the publication date",value=datetime.date.today())ifst.button(label="Add entry post",help="Here you safe a new entry post!",):add_data(db_connection,INSERT_SQL_SCRIPTS,blog_author,blog_title,blog_content,blog_post_date)st.success(f"Post: {blog_title} saved")# elif choice == "Update Posts":# unique_titles = [article[0] for article in view_all_article_titles(db_connection, SELECT_DISTINCT_SQL_SCRIPTS)]# st.subheader("Update Posts")# st.markdown("Select a article to delete on the follow select list")# update_blog_by_title = st.selectbox(# "Unique Title", unique_titles,# help="Select a choice from the select list!"# )# if st.button(# label="Update (This Can't Be Undone!)",# help="I hope you know what you're getting into!",# ):# update_data(db_connection, update_blog_by_title)# st.warning(f"Updated: '{update_blog_by_title}'")elifchoice=="Search...":st.subheader("Search Articles")search_term=st.text_input(label="Enter Search Term",help="Enter the Search Term!",placeholder="Example fot title, Data science for Python or Example fot author, Leonardo Caballero",)search_choice=st.radio(label="Field to Search By",options=("title","author"),help="Check one criteria option to search!",horizontal=True,)ifst.button(label="Search",help="I hope you will found what do you search!",):ifsearch_choice=="title":article_result=get_blog_by_title(db_connection,search_term)elifsearch_choice=="author":article_result=get_blog_by_author(db_connection,search_term)iflen(article_result)==0:st.markdown(NOTFOUND_SEARCH_MSG_HTML_TPL.format(div_bg_color=PRIMARY_COLOR,),unsafe_allow_html=True)else:forarticleinarticle_result:post_author=article[0]post_title=article[1]post_content=article[2]post_date=article[3]# st.text(f"Reading Time:{readingTime(post_content)}")st.markdown(ENTRY_DETAILS_HTML_TPL.format(div_bg_color=PRIMARY_COLOR,title=post_title,author=post_author,date=post_date),unsafe_allow_html=True,)st.markdown(ENTRY_CONTENT_MSG_HTML_TPL.format(content=post_content),unsafe_allow_html=True)elifchoice=="Manage Blog":st.subheader("Manage Articles")result=view_all_articles(db_connection,SELECT_SQL_SCRIPTS)iflen(result)==0:st.markdown(NOTFOUND_ENTRY_MSG_HTML_TPL.format(div_bg_color=PRIMARY_COLOR,),unsafe_allow_html=True)else:clean_db=pd.DataFrame(result,columns=["Author","Title","Articles","Post Date"])st.dataframe(clean_db)unique_titles=[article[0]forarticleinview_all_article_titles(db_connection,SELECT_DISTINCT_SQL_SCRIPTS)]st.subheader("Delete Article")st.markdown("Select a article to delete on the follow select list")delete_blog_by_title=st.selectbox("Unique Title",unique_titles,help="Select a choice from the select list!")new_df=clean_dbifst.button(label="Delete (This Can't Be Undone!)",help="I hope you know what you're getting into!",):delete_data(db_connection,delete_blog_by_title)st.warning(f"Deleted: '{delete_blog_by_title}'")st.subheader("Generate Graphics")st.markdown("Select the checkbox for generate graphics")ifst.checkbox(label="Metrics",help="Check this option for generate the Metrics Stats!",):new_df["Length"]=new_df["Articles"].str.len()st.dataframe(new_df)st.subheader("Author Stats")new_df["Author"].value_counts().plot(kind="bar")st.pyplot()st.subheader("Author Stats")new_df["Author"].value_counts().plot.pie(autopct="%1.1f%%")st.pyplot()ifst.checkbox(label="Word Cloud",help="Check this option for generate a Term Word Cloud!",):st.subheader("Generate Word Cloud")# text = new_df['Articles'].iloc[0]text=",".join(new_df["Articles"])wordcloud=WordCloud().generate(text)plt.pyplot.imshow(wordcloud,interpolation="bilinear")plt.pyplot.axis("off")st.pyplot()ifst.checkbox(label="Bar Horizontal Plot",help="Check this option for generate a Bar Horizontal Plot!",):st.subheader("Length of Articles")new_df=clean_dbnew_df["Length"]=new_df["Articles"].str.len()barh_plot=new_df.plot.barh(x="Author",y="Length",figsize=(20,10))st.pyplot()elifchoice=="About":render_about()if__name__=="__main__":connection=create_connection(DB)ifconnectionisnotNone:main(connection)else:logging.error(f"ERROR! cannot create the database connection to the {DB} file.")
Archivo db_initial.py
Módulo que agregar datos iniciales de la publicación de la entrada del blog.
importloggingimportosimportsqlite3fromfakerimportFakerfromdbimportcreate_connection,create_tablefromsettingsimport(ARTICLES_RANGE,DB,INSERT_SQL_SCRIPTS,TABLE_SQL_SCRIPTS,)# Logging Applogging.basicConfig(level=logging.INFO)# Fakerfake=Faker()# Functionsdefgenerate_data_fake(faker):"""Generate data fake for articles table Args: faker (faker.proxy.Faker): Faker proxy object Returns: list: Data faker records list """article,articles=(),[]for_inrange(ARTICLES_RANGE):article=(faker.name(),faker.sentence(),str(faker.texts()).replace("['","").replace("']","").replace("\\n","<br/>").replace(".', '",". "),faker.past_date())articles.append(article)returnarticlesdefadd_data_initial(db_connection,sql_script,sql_script_values):"""Add data initial of Blog entry post Args: db_connection (Connection): SQLite database connection representation sql_script (str): SQL script to execute sql_script_values (list): Data faker records list Returns: list: Records list """try:cursor=db_connection.cursor()cursor.executemany(sql_script,sql_script_values)db_connection.commit()logging.info("¡{} record(s) was(were) successfully added to the table!".format(cursor.rowcount))exceptsqlite3.Erroraserror:logging.error(f"The add of record(s) in the table failed! {error}")finally:ifcursor:cursor.close()logging.info("The cursor for data initial of blog entry posts was closed successfully!")ifdb_connection:db_connection.close()logging.info("Disconnect to database 'simple_blog.sqlite3' was closed successfully!")if__name__=="__main__":connection=create_connection(DB)ifconnectionisnotNone:create_table(connection,TABLE_SQL_SCRIPTS)add_data_initial(connection,INSERT_SQL_SCRIPTS,generate_data_fake(fake))else:logging.error(f"ERROR! cannot create the database connection to the {DB} file.")
""" SQLite database functions """importloggingimportosimportsqlite3defcreate_connection(path):"""Create a database connection to a SQLite database Args: path (str): The full path used to read the database Returns: db_connection (Connection): SQLite database connection representation """db_connection=Noneifos.path.exists(path):try:db_connection=sqlite3.connect(path)logging.info(f"Connection to database '{os.path.basename(path)}' was successful!")exceptsqlite3.ProgrammingErrorase:print(f"ERROR: A programming error has occurred: '{e}'!")exceptsqlite3.OperationalErrorase:print(f"ERROR: The following occurred: '{e}'")# finally:# if db_connection:# db_connection.close()# logging.info("The database connection was closed successfully!")else:try:db_connection=sqlite3.connect(path)logging.info(f"Database creation '{os.path.basename(path)}' was successful!")logging.info(f"Connection to database '{os.path.basename(path)}' was established successfully!")exceptsqlite3.ProgrammingErrorase:print(f"ERROR: A programming error has occurred: '{e}'!")exceptsqlite3.OperationalErrorase:print(f"ERROR: The following occurred: '{e}'")# finally:# if db_connection:# db_connection.close()# logging.info("The database connection was closed successfully!")returndb_connectiondefcreate_table(db_connection,sql_script):"""Create Database table Args: db_connection (Connection): SQLite database connection representation sql_script (str): SQL script to execute """try:cursor=db_connection.cursor()cursor.execute(sql_script)db_connection.commit()logging.info("The table was created successfully!")exceptsqlite3.Erroraserror:logging.error(f"Table creation failed! {error}")finally:ifcursor:cursor.close()logging.info("The cursor for create database table was closed successfully!")# if db_connection:# db_connection.close()# logging.info("The database connection was closed successfully!")
### SQLite ######################################
DB_FILE=simple_blog.sqlite3
### Simple Blog App #############################
# Application title name
APP_TITLE=Simple Blog
# Number of range of blog posts to create
ARTICLES_RANGE=3
# Primary accent color for interactive elements.
PRIMARY_COLOR=#A6BB8D
# Background color for the main content area.
BACKGROUND_COLOR=#3C6255
# Background color used for the sidebar and most interactive widgets.
SECONDARY_BACKGROUND_COLOR=#61876E
# Color used for almost all text.
TEXT_COLOR=#EAE7B1
""" Simple Blog Settings """importosfromdotenvimportload_dotenv### DotENV #################################################################load_dotenv()# Name of the database to which to connect.DB_FILE=os.getenv("DB_FILE")# Application title nameAPP_TITLE=os.getenv("APP_TITLE")# Number of range of blog posts to createARTICLES_RANGE=int(os.getenv("ARTICLES_RANGE"))# Color Palette: #3C6255 #61876E #A6BB8D #EAE7B1# Color Hunt https://colorhunt.co/palette/3c625561876ea6bb8deae7b1# Primary accent color for interactive elements.# using by Blog Entry Post Information SheetPRIMARY_COLOR=os.getenv("PRIMARY_COLOR")# Background color for the main content area.BACKGROUND_COLOR=os.getenv("BACKGROUND_COLOR")# Background color used for the sidebar and most interactive widgets.# using by Blog Header Main Title ColorSECONDARY_BACKGROUND_COLOR=os.getenv("SECONDARY_BACKGROUND_COLOR")# Color used for almost all text.# using by Blog Header Main Title Background ColorTEXT_COLOR=os.getenv("TEXT_COLOR")### SQLite3 ################################################################DB_PATH=os.path.dirname(os.path.abspath(__file__))+os.sep# DB Fileif"DB_PATH"inglobals()and"DB_FILE"inglobals():DB=DB_PATH+DB_FILE# Script CREATE TABLE SQL a usar al crear la tablaTABLE_SQL_SCRIPTS=""" CREATE TABLE IF NOT EXISTS articles ( author TEXT NOT NULL, title TEXT NOT NULL UNIQUE, content TEXT NOT NULL, post_date DATE NOT NULL );"""# Script INSERT SQL a usar al ingresar datosINSERT_SQL_SCRIPTS=""" INSERT INTO articles (author, title, content, post_date) VALUES (?, ?, ?, ?);"""# SELECT SQL script to use when querying dataSELECT_SQL_SCRIPTS="""SELECT * FROM articles;"""# SELECT DISTINCT SQL script to use when querying data by titleSELECT_DISTINCT_SQL_SCRIPTS="""SELECT DISTINCT title FROM articles;"""
Archivo simple_blog.sqlite3
Archivo de la hoja de calculo de SQLite llamado simple_blog.sqlite3
la cual no se incluye ya que cada vez que se inicia el programa app.py, para
cuidar la creación de los datos iniciales.
Archivo .streamlit/config.toml
Archivo de configuración de proyecto Streamlit.
1 2 3 4 5 6 7 8 910111213141516171819
[theme]# Primary accent color for interactive elements.primaryColor="#A6BB8D"# Background color for the main content area.backgroundColor="#3C6255"# Background color used for the sidebar and most interactive widgets.secondaryBackgroundColor="#61876E"# Color used for almost all text.textColor="#EAE7B1"# Font family for all text in the app, except code blocks. One of "sans serif", "serif", or "monospace".# Default: "sans serif"font="sans serif"[deprecation]showPyplotGlobalUse=false
A continuación se presenta la ejecución de una demostración de SimpleBlog,
ejecutando los siguientes comandos correspondiente a tu sistema operativo:
Antes de ejecutar debes instalar sus dependencias, con el siguiente comando:
$ pip install -r requirements.txt
Ademas debe instalar y editar el archivo .env, con el siguiente comando:
$ cp .env.example .env
$ nano .env
Truco
El archivo .env se definen las configuraciones de conexión a la base de datos,
puede modificarlo cambiar valores de la conexión.
Truco
Para ejecutar el código fuente de esta practica debe invocar primero al modulo db_initial.py,
abra una consola de comando, acceda al directorio donde se encuentra la estructura previa
y ejecute el siguiente comando:
$ python db_initial.py
El anterior código al ejecutar debe mostrar el siguiente mensaje:
INFO:root:Database creation 'simple_blog.sqlite3' was successful!INFO:root:Connection to database 'simple_blog.sqlite3' was established successfully!INFO:root:The table was created successfully!INFO:root:The cursor for create database table was closed successfully!INFO:root:¡3 record(s) was(were) successfully added to the table!INFO:root:The cursor for data initial of blog entry posts was closed successfully!INFO:root:Disconnect to database 'simple_blog.sqlite3' was closed successfully!
Truco
Para ejecutar el código fuente de esta practica debe invocar al modulo app.py,
abra una consola de comando, acceda al directorio donde se encuentra la estructura previa
y ejecute el siguiente comando:
$ streamlit run app.py
El anterior comando al ejecutar debe mostrar el siguiente mensaje:
You can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://172.28.94.109:8501
Antes de ejecutar debes instalar sus dependencias, con el siguiente comando:
> pip install -r requirements.txt
Ademas debe instalar y editar el archivo .env, con el siguiente comando:
> COPY .env.example .env> notepad.exe .env
Truco
El archivo .env se definen las configuraciones de conexión a la base de datos,
puede modificarlo cambiar valores de la conexión.
Truco
Para ejecutar el código fuente de esta practica debe invocar primero al modulo db_initial.py,
abra una consola de comando, acceda al directorio donde se encuentra la estructura previa
y ejecute el siguiente comando:
> python db_initial.py
El anterior código al ejecutar debe mostrar el siguiente mensaje:
INFO:root:Database creation 'simple_blog.sqlite3' was successful!INFO:root:Connection to database 'simple_blog.sqlite3' was established successfully!INFO:root:The table was created successfully!INFO:root:The cursor for create database table was closed successfully!INFO:root:¡3 record(s) was(were) successfully added to the table!INFO:root:The cursor for data initial of blog entry posts was closed successfully!INFO:root:Disconnect to database 'simple_blog.sqlite3' was closed successfully!
Truco
Para ejecutar el código fuente de esta practica debe invocar al modulo app.py,
abra una consola de comando, acceda al directorio donde se encuentra la estructura previa
y ejecute el siguiente comando:
> streamlit run app.py
El anterior comando al ejecutar debe mostrar el siguiente mensaje:
You can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://172.28.94.109:8501
Nota
LocalURL
Dirección local de tu PC donde ejecuta esta demostración, valor por
defecto es http://localhost:8501
NetworkURL
Dirección de la red local de tu PC donde donde puede compartir la forma
como accede a esta demostración.
Abra el navegador web en la dirección local definida en el valor LocalURL:
De esta forma tiene una práctica real de crear un CRUD, usando fuente de datos
una base de datos SQLite y usado la librería Streamlit.
Ver también
Consulte la sección de lecturas suplementarias
del entrenamiento para ampliar su conocimiento en esta temática.