Ritesh1035 commited on
Commit
98cf96b
·
verified ·
1 Parent(s): 139faa5

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +186 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,188 @@
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
+ import json
4
+ from typing import Optional
5
 
6
+ # Configure Streamlit page
7
+ st.set_page_config(
8
+ page_title="Customer Management System",
9
+ layout="wide"
10
+ )
11
+
12
+ # FastAPI base URL
13
+ BASE_URL = "https://ritesh1035-cms-apis.hf.space"
14
+
15
+ # Helper functions
16
+ def make_request(method, endpoint, data=None):
17
+ """Make HTTP request to FastAPI backend"""
18
+ url = f"{BASE_URL}{endpoint}"
19
+ try:
20
+ if method == "GET":
21
+ response = requests.get(url)
22
+ elif method == "POST":
23
+ response = requests.post(url, json=data)
24
+ elif method == "PUT":
25
+ response = requests.put(url, json=data)
26
+ elif method == "DELETE":
27
+ response = requests.delete(url)
28
+
29
+ return response
30
+ except requests.exceptions.ConnectionError:
31
+ st.error("Cannot connect to FastAPI server. Make sure it's running on http://localhost:8000")
32
+ return None
33
+
34
+ # Main title
35
+ st.title("Customer Management System")
36
+
37
+ # Sidebar for operation selection
38
+ st.sidebar.header("Choose An Operations")
39
+ operation = st.sidebar.selectbox(
40
+ "Select Operation:",
41
+ ["View All Customers", "Add Customer", "Update Customer", "Delete Customer"]
42
+ )
43
+
44
+ # Main content area
45
+ if operation == "View All Customers":
46
+ st.header("Customer List")
47
+
48
+ if st.button("Refresh List"):
49
+ response = make_request("GET", "/Customer")
50
+ if response and response.status_code == 200:
51
+ customers = response.json()
52
+ if customers:
53
+ st.success(f"Found {len(customers)} customers")
54
+
55
+ # Simple table display
56
+ for customer in customers:
57
+ st.write("---")
58
+ col1, col2 = st.columns(2)
59
+ with col1:
60
+ st.write(f"**ID:** {customer['id']}")
61
+ st.write(f"**Name:** {customer['name']}")
62
+ st.write(f"**Email:** {customer['email']}")
63
+ with col2:
64
+ st.write(f"**Phone:** {customer.get('phone', 'Not provided')}")
65
+ st.write(f"**Address:** {customer.get('address', 'Not provided')}")
66
+ else:
67
+ st.info("No customers found")
68
+ elif response:
69
+ st.error(f"Failed to fetch customers: {response.status_code}")
70
+
71
+ elif operation == "Add Customer":
72
+ st.header("Add New Customer")
73
+
74
+ with st.form("add_customer"):
75
+ customer_name = st.text_input("Name (required)")
76
+ customer_email = st.text_input("Email (required)")
77
+ customer_phone = st.text_input("Phone (optional)")
78
+ customer_address = st.text_area("Address (optional)")
79
+
80
+ if st.form_submit_button("Add Customer"):
81
+ if not customer_name or not customer_email:
82
+ st.error("Name and Email are required")
83
+ else:
84
+ # Auto-generate ID based on existing customers count
85
+ try:
86
+ existing_customers = requests.get("http://localhost:8000/Customer").json()
87
+ customer_id = len(existing_customers) + 1
88
+ except:
89
+ customer_id = 1
90
+
91
+ customer_data = {
92
+ "id": customer_id,
93
+ "name": customer_name,
94
+ "email": customer_email,
95
+ "phone": customer_phone if customer_phone else None,
96
+ "address": customer_address if customer_address else None
97
+ }
98
+
99
+ response = make_request("POST", "/Customer", customer_data)
100
+ if response and response.status_code == 200:
101
+ st.success(f"Customer '{customer_name}' added successfully")
102
+ elif response:
103
+ st.error(f"Failed to add customer: {response.status_code}")
104
+
105
+ elif operation == "Update Customer":
106
+ st.header("Update Customer")
107
+
108
+ update_id = st.number_input("Customer ID to Update", min_value=1, step=1)
109
+
110
+ if st.button("Load Customer"):
111
+ response = make_request("GET", "/Customer")
112
+ if response and response.status_code == 200:
113
+ customers = response.json()
114
+ customer = next((c for c in customers if c['id'] == update_id), None)
115
+
116
+ if customer:
117
+ st.session_state.update_customer = customer
118
+ st.success(f"Loaded: {customer['name']}")
119
+ else:
120
+ st.error(f"Customer with ID {update_id} not found")
121
+
122
+ if 'update_customer' in st.session_state:
123
+ customer = st.session_state.update_customer
124
+
125
+ with st.form("update_customer_form"):
126
+ new_name = st.text_input("Name", value=customer['name'])
127
+ new_email = st.text_input("Email", value=customer['email'])
128
+ new_phone = st.text_input("Phone", value=customer.get('phone', ''))
129
+ new_address = st.text_area("Address", value=customer.get('address', ''))
130
+
131
+ if st.form_submit_button("Update Customer"):
132
+ if not new_name or not new_email:
133
+ st.error("Name and Email are required")
134
+ else:
135
+ updated_data = {
136
+ "id": update_id,
137
+ "name": new_name,
138
+ "email": new_email,
139
+ "phone": new_phone if new_phone else None,
140
+ "address": new_address if new_address else None
141
+ }
142
+
143
+ response = make_request("PUT", f"/Customer/{update_id}", updated_data)
144
+ if response and response.status_code == 200:
145
+ st.success(f"Customer updated successfully")
146
+ del st.session_state.update_customer
147
+ st.rerun()
148
+ elif response:
149
+ st.error(f"Failed to update customer: {response.status_code}")
150
+
151
+ elif operation == "Delete Customer":
152
+ st.header("Delete Customer")
153
+
154
+ st.warning("Warning: This action cannot be undone")
155
+
156
+ delete_id = st.number_input("Customer ID to Delete", min_value=1, step=1)
157
+
158
+ if st.button("Preview Customer"):
159
+ response = make_request("GET", "/Customer")
160
+ if response and response.status_code == 200:
161
+ customers = response.json()
162
+ customer = next((c for c in customers if c['id'] == delete_id), None)
163
+
164
+ if customer:
165
+ st.info(f"Customer to delete: {customer['name']} ({customer['email']})")
166
+ st.session_state.delete_customer = customer
167
+ else:
168
+ st.error(f"Customer with ID {delete_id} not found")
169
+
170
+ if 'delete_customer' in st.session_state:
171
+ customer = st.session_state.delete_customer
172
+ st.error(f"Are you sure you want to delete {customer['name']}?")
173
+
174
+ col1, col2 = st.columns(2)
175
+ with col1:
176
+ if st.button("Yes, Delete"):
177
+ response = make_request("DELETE", f"/Customer/{delete_id}")
178
+ if response and response.status_code == 200:
179
+ st.success(f"Customer deleted successfully")
180
+ del st.session_state.delete_customer
181
+ st.rerun()
182
+ elif response:
183
+ st.error(f"Failed to delete customer: {response.status_code}")
184
+
185
+ with col2:
186
+ if st.button("Cancel"):
187
+ del st.session_state.delete_customer
188
+ st.rerun()