18 hours ago
—
Introduction:
In this tutorial, we’ll walk through the process of creating a MongoDB CRUD (Create, Read, Update, Delete) application using Streamlit, a popular Python library for building interactive web applications. We’ll build a simple web interface for interacting with a MongoDB database, allowing users to add, view, edit, and delete data.
Setting Up MongoDB:
First, let’s ensure you have a MongoDB database set up. You can create a free MongoDB Atlas account and set up a cluster to host your database. Make sure to note down your connection string and database name, as we’ll need them later.
Setting Up the Environment:
We’ll use Python for this project, so make sure you have Python installed on your system. Create a new directory for your project and set up a virtual environment using `venv` or `conda`:
“`
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
# For Windows
myenvScriptsactivate
# For macOS/Linux
source myenv/bin/activate
“`
Now, let’s install the required packages using pip and create a `requirements.txt` file:
“`
pip install streamlit pymongo pandas
pip freeze > requirements.txt
“`
Creating the Streamlit App:
Now, let’s create our Streamlit app. We’ll start by importing the necessary libraries and setting up the connection to our MongoDB database:
“`python
import streamlit as st
from pymongo import MongoClient
import pandas as pd
import base64
# Connect to MongoDB
password = st.secrets[‘password’]
client = MongoClient(‘mongodb+srv://username:’ + password + ‘@cluster0.woxnlek.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0’)
db = client[‘your_database_name’]
collection = db[‘your_collection_name’]
“`
Next, we’ll define the CSS styles for our navigation bar using Tailwind CSS:
“`python
st.markdown(
“””
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
background-color: #f0f0f0;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
border-radius: 8px;
margin-bottom: 1.5rem;
}
.navbar-item {
margin-right: 1rem;
}
“””
, unsafe_allow_html=True
)
“`
Now, let’s define the main function for our Streamlit app and implement the Add Data and View Data functionalities:
“`python
def main():
st.title(“MongoDB CRUD App”)
# Navigation
page = st.radio(“Navigation”, [“Add Data”, “View Data”])
if page == “Add Data”:
add_data()
elif page == “View Data”:
view_data()
def add_data():
st.header(“Add Data”)
# Input fields for data
name = st.text_input(“Enter Name”)
age = st.number_input(“Enter Age”, min_value=0)
email = st.text_input(“Enter Email”)
# Button to add data to MongoDB
if st.button(“Add Data”):
if name and age and email:
data = {“name”: name, “age”: age, “email”: email}
collection.insert_one(data)
st.success(“Data added successfully!”)
else:
st.warning(“Please fill in all fields.”)
def view_data():
st.header(“View Data”)
# Retrieve data from MongoDB
data = list(collection.find())
# Display data in a table
if data:
df = pd.DataFrame(data)
st.dataframe(df)
# Option to edit or delete data
st.sidebar.title(“Actions”)
action = st.sidebar.selectbox(“Select action”, [“Edit Data”, “Delete Data”])
if action == “Edit Data”:
edit_data(data)
elif action == “Delete Data”:
delete_data(data)
# Download CSV button
csv_data = df.to_csv(index=False)
b64 = base64.b64encode(csv_data.encode()).decode()
href = f’Download CSV File’
st.markdown(href, unsafe_allow_html=True)
else:
st.warning(“No data found.”)
# Implementing edit_data() and delete_data() functions omitted for brevity
if __name__ == “__main__”:
main()
“`
Conclusion:
In this tutorial, we’ve learned how to build a MongoDB CRUD application using Streamlit and Tailwind CSS. With Streamlit’s simplicity and interactivity and Tailwind CSS’s easy-to-use utility classes, we’ve created a web interface for managing data in a MongoDB database. You can further enhance this application by adding authentication, validation, and more advanced features. Happy coding!