geeksiddhant commited on
Commit
a26bbe7
·
verified ·
1 Parent(s): 295c191

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +151 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,153 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import requests
3
+ from typing import List, Optional
4
 
5
+ # API base URL
6
+ BASE_URL = "https://geeksiddhant-enrollmentapi.hf.space"
7
+
8
+ # Initialize session state for customers list
9
+ if 'customers' not in st.session_state:
10
+ st.session_state.customers = []
11
+
12
+ def fetch_customers():
13
+ """Fetch all customers from the API"""
14
+ try:
15
+ response = requests.get(f"{BASE_URL}/customers")
16
+ if response.status_code == 200:
17
+ st.session_state.customers = response.json()
18
+ except requests.exceptions.RequestException as e:
19
+ st.error(f"Error fetching customers: {str(e)}")
20
+
21
+ def create_customer(name: str, email: str, phone: Optional[str] = None, address: Optional[str] = None):
22
+ """Create a new customer"""
23
+ try:
24
+ # Find the next available ID
25
+ next_id = max([c['id'] for c in st.session_state.customers], default=0) + 1
26
+
27
+ customer_data = {
28
+ "id": next_id,
29
+ "name": name,
30
+ "email": email,
31
+ "phone": phone,
32
+ "address": address
33
+ }
34
+
35
+ response = requests.post(f"{BASE_URL}/customers", json=customer_data)
36
+ if response.status_code == 200:
37
+ st.success("Customer created successfully!")
38
+ fetch_customers()
39
+ else:
40
+ st.error(f"Error creating customer: {response.text}")
41
+ except requests.exceptions.RequestException as e:
42
+ st.error(f"Error creating customer: {str(e)}")
43
+
44
+ def update_customer(customer_id: int, name: str, email: str, phone: Optional[str] = None, address: Optional[str] = None):
45
+ """Update an existing customer"""
46
+ try:
47
+ customer_data = {
48
+ "id": customer_id,
49
+ "name": name,
50
+ "email": email,
51
+ "phone": phone,
52
+ "address": address
53
+ }
54
+
55
+ response = requests.put(f"{BASE_URL}/customers/{customer_id}", json=customer_data)
56
+ if response.status_code == 200:
57
+ st.success("Customer updated successfully!")
58
+ fetch_customers()
59
+ else:
60
+ st.error(f"Error updating customer: {response.text}")
61
+ except requests.exceptions.RequestException as e:
62
+ st.error(f"Error updating customer: {str(e)}")
63
+
64
+ def delete_customer(customer_id: int):
65
+ """Delete a customer"""
66
+ try:
67
+ response = requests.delete(f"{BASE_URL}/customers/{customer_id}")
68
+ if response.status_code == 200:
69
+ st.success("Customer deleted successfully!")
70
+ fetch_customers()
71
+ else:
72
+ st.error(f"Error deleting customer: {response.text}")
73
+ except requests.exceptions.RequestException as e:
74
+ st.error(f"Error deleting customer: {str(e)}")
75
+
76
+ # Streamlit UI
77
+ st.title("Customer Management System")
78
+
79
+ # Sidebar for navigation
80
+ page = st.sidebar.selectbox("Choose an operation", ["View Customers", "Add Customer", "Update Customer", "Delete Customer"])
81
+
82
+ # Fetch customers on initial load
83
+ fetch_customers()
84
+
85
+ if page == "View Customers":
86
+ st.header("All Customers")
87
+ if st.session_state.customers:
88
+ for customer in st.session_state.customers:
89
+ st.write(f"**ID:** {customer['id']}")
90
+ st.write(f"**Name:** {customer['name']}")
91
+ st.write(f"**Email:** {customer['email']}")
92
+ if customer.get('phone'):
93
+ st.write(f"**Phone:** {customer['phone']}")
94
+ if customer.get('address'):
95
+ st.write(f"**Address:** {customer['address']}")
96
+ st.write("---")
97
+ else:
98
+ st.info("No customers found.")
99
+
100
+ elif page == "Add Customer":
101
+ st.header("Add New Customer")
102
+ with st.form("add_customer_form"):
103
+ name = st.text_input("Name")
104
+ email = st.text_input("Email")
105
+ phone = st.text_input("Phone (optional)")
106
+ address = st.text_area("Address (optional)")
107
+
108
+ submitted = st.form_submit_button("Add Customer")
109
+ if submitted:
110
+ if name and email:
111
+ create_customer(name, email, phone, address)
112
+ else:
113
+ st.warning("Please fill in the required fields (Name and Email)")
114
+
115
+ elif page == "Update Customer":
116
+ st.header("Update Customer")
117
+ if st.session_state.customers:
118
+ customer_id = st.selectbox(
119
+ "Select Customer to Update",
120
+ options=[c['id'] for c in st.session_state.customers]
121
+ )
122
+
123
+ # Get the selected customer's data
124
+ selected_customer = next((c for c in st.session_state.customers if c['id'] == customer_id), None)
125
+
126
+ if selected_customer:
127
+ with st.form("update_customer_form"):
128
+ name = st.text_input("Name", value=selected_customer['name'])
129
+ email = st.text_input("Email", value=selected_customer['email'])
130
+ phone = st.text_input("Phone", value=selected_customer.get('phone', ''))
131
+ address = st.text_area("Address", value=selected_customer.get('address', ''))
132
+
133
+ submitted = st.form_submit_button("Update Customer")
134
+ if submitted:
135
+ if name and email:
136
+ update_customer(customer_id, name, email, phone, address)
137
+ else:
138
+ st.warning("Please fill in the required fields (Name and Email)")
139
+ else:
140
+ st.info("No customers available to update.")
141
+
142
+ elif page == "Delete Customer":
143
+ st.header("Delete Customer")
144
+ if st.session_state.customers:
145
+ customer_id = st.selectbox(
146
+ "Select Customer to Delete",
147
+ options=[c['id'] for c in st.session_state.customers]
148
+ )
149
+
150
+ if st.button("Delete Customer"):
151
+ delete_customer(customer_id)
152
+ else:
153
+ st.info("No customers available to delete.")