How to create a Contact Web App using streamlit

posted 5 min read

At one point, we began programming in Python using just the terminal. We would prompt the user to input their name, and then print the output “Hello name”. Today, we can accomplish this easily in a browser using the powerful Streamlit Python web framework.

We will create a simple contact list app or application with the use of Streamlit as simple as possible. You will also learn to install streamlit on your computer and run it in your browser locally. Streamlit can also be deployed in the cloud, allowing others to use it, but we will cover that topic in a future discussion.

A. What is Streamlit?

Streamlit is a tool to create web applications using Python. You don't need to know about html, css, and javascript to build an app, with Streamlit, you can make apps that show charts, maps, machine learning predictions, etc. It is free and its source code is open to the public!

B. Create a Contact List App

The user interface is consist of two main components, the Form and the Text components. The Form component contains the name, email address input components, and a button component to save the user info. The Text component displays the saved user input.

C. Requirements

1. Python

Download Python, select version 3.10 and above.

2. Streamlit

Open your terminal, or powershell and install streamlit with pip.

pip install streamlit

D. Code snippets

main.py

import streamlit as st

# Create a form for user name and email address.
with st.form(key='user_info_key', clear_on_submit=False):
    name = st.text_input('Name')
    email = st.text_input('Email')
    submit = st.form_submit_button('Save')

if submit:
    # Save the user info in a dictionary.
    user_info = {'Name': name, 'Email': email}
    st.write(user_info)

And we are done.

1. Run the application

Open your terminal and change to a directory where main.py is located.

c:\streamlit\form_project>streamlit run main.py

Then visit the url "http://localhost:8501" in your browser.

E. App Enhancement num 1

That app does not save the user input. It only displays the current contents of the form. Past input are not saved. I am going to revise that code to save the past input.

1. Streamlit variable

We need a variable to store all the user data. Streamlit provides a means to create variables through its session state which is a dictionary. In our case we will create a list of dict.

Example:

  • Import the streamlit
  • Define a variable by creating a dict key.
  • Initialize the variable.
import streamlit as st

if 'contact' not in st.session_state:
    st.session_state['contact'] = []

"contact" is the key to the streamlit's internal session state dictionary. Our variable "st.session_state['contact']" is initialized with an empty list.

2. Revised code num 1

main.py

import streamlit as st


# Create a variable to store the user info.
if 'contact' not in st.session_state:
    st.session_state['contact'] = []

# Create a form for user name and email address.
with st.form(key='user_info_key', clear_on_submit=False):
    name = st.text_input('Name')
    email = st.text_input('Email')
    submit = st.form_submit_button('Save')

if submit:
    # Save the user info in a dictionary.
    user_info = {'Name': name, 'Email': email}

    # Add the user data to our variable. Use append since it is a list.
    st.session_state['contact'].append(user_info)

    # Show the table
    st.dataframe(st.session_state['contact'])

F. App Enhancement num 2

The improvement num 1 might not be enough because once you refresh the page, the session is lost along with the data stored in our variable. To solve this issue, we will write the user data directly to a file say "contact.csv".

1. Algorithm

  1. Open the csv file and create dataframe no. 1 using Pandas library.
  2. Check user input, if there is, create dataframe no. 2.
  3. Concatenate the two dataframes and save it as dataframe no. 1
  4. Display the dataframe no. 1.
  5. Save dataframe no. 1 back to csv file that we opened in step 1.
Caution: When Streamlit reads our script from top to bottom or step 1 to step 5, the dataframe no. 1 is created again per step 1. This dataframe is different because in step 5, we had saved a user data.

2. Revised code num 2

We no longer use our session state variable in this case because we use the csv file.

main.py

import streamlit as st
import pandas as pd

CSVFN = 'contact.csv'
HEADER = ['Name', 'Email']

# Open the csv file and convert to dataframe.
try:
    df1 = pd.read_csv(CSVFN)
except FileNotFoundError:
    df1 = pd.DataFrame(columns=HEADER)

# Create a form for user name and email address.
with st.form(key='user_info_key', clear_on_submit=False):
    name = st.text_input('Name')
    email = st.text_input('Email')
    submit = st.form_submit_button('Save')

if submit:
    # Save the user info in a dictionary.
    user_info = {'Name': name, 'Email': email}

    df2 = pd.DataFrame([user_info])
    df1 = pd.concat([df1, df2], ignore_index=True)

# Show the saved data in a table.
st.dataframe(df1, use_container_width=True)

# Save the dataframe to csv file.
df1.to_csv(CSVFN, index=False)

This is how it would look like.

G. Code Maintenance

The code has been deployed as a repository in bitbucket to maintain and update it comfortably.

H. Summary

Streamlit is a Python framework used to build web applications. We build a contact application where user's name and email are saved in a csv file.

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

How to create an Income and Expense App in Streamlit

Brando - Nov 19, 2023

Learn how to build a user-friendly, conversational Telegram bot with python

Astra Bertelli - Apr 30, 2024

How to read a file and search specific word locations in Python

Brando - Nov 8, 2023

How to Fix the TypeError: cannot use a string pattern on a bytes-like object Error in Python

Cornel Chirchir - Oct 29, 2023

Create a python Telegram bot, plain, simple and production-ready

Astra Bertelli - Apr 24, 2024
chevron_left