Skip to content

Commit 7d17dd0

Browse files
committed
changes suggested by Nithish
1 parent ef402b4 commit 7d17dd0

File tree

1 file changed

+30
-31
lines changed

1 file changed

+30
-31
lines changed

tutorial/markdown/python/streamlit/flight_search_streamlit_couchbase.md

Lines changed: 30 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,8 @@ streamlit hello
155155

156156
If everything is set up correctly, a browser window should open with Streamlit's demo application.
157157

158-
### Implement Data Fetching Functions
159-
To optimize performance, data retrieval functions are cached using `@st.cache_data`, which stores previously fetched data to prevent redundant queries and speed up the app. However, the `_connection` object is intentionally not cached (indicated by the underscore prefix) to ensure a fresh database connection is established each time. Caching the connection could lead to issues with stale or expired sessions, potentially causing failed queries or inconsistent data retrieval. For more details, refer to the official documentation: [Streamlit `st.cache_data`](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_data).
158+
### Implement Data Fetching Functions
159+
To optimize performance, data retrieval functions are cached using `@st.cache_data`, which stores previously fetched data to prevent redundant queries and speed up the app. However, the `_connection` argument is not cached because database connection objects are not hashable. The underscore prefix is used to explicitly exclude it from caching, ensuring that Streamlit does not attempt to hash the connection. Since `@st.cache_data` requires function arguments to be hashable, unhashable objects like database connections must be excluded to avoid errors. For more details, refer to the official documentation: [Streamlit `st.cache_data`](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_data).
160160

161161
`get_all_airports(_connection)`: Fetches airport details.
162162
```python
@@ -180,13 +180,7 @@ This function fetches route information from the `route` collection in the `trav
180180
```python
181181
@st.cache_data
182182
def get_routes_for_airports(_connection, selected_airports_df):
183-
airports_faa = "[" # Initialize a string to store FAA codes in a list format
184-
for i in range(len(selected_airports_df)):
185-
if i != len(selected_airports_df) - 1:
186-
airports_faa += f'"{(selected_airports_df.iloc[i])["faa"]}", ' # Append each FAA code with a comma
187-
else:
188-
airports_faa += f'"{(selected_airports_df.iloc[i])["faa"]}"' # Append last FAA code without a comma
189-
airports_faa += "]"
183+
airports_faa = str(selected_airports_df["faa"].to_list()) # Initialize a string to store FAA codes in a list format
190184
query = f"""
191185
SELECT * FROM `travel-sample`.`inventory`.`route`
192186
WHERE (sourceairport IN {airports_faa} AND destinationairport IN {airports_faa});
@@ -296,13 +290,7 @@ This function retrieves hotel data from the `travel-sample.inventory.hotel` coll
296290
```python
297291
@st.cache_data
298292
def get_all_hotels(_connection, cities):
299-
cities_str = "[" # Initialize the string for city names
300-
for i in range(len(cities)):
301-
if i != len(cities) - 1:
302-
cities_str += f'"{cities[i]}", ' # Add city name with a comma
303-
else:
304-
cities_str += f'"{cities[i]}"' # Add last city without a comma
305-
cities_str += "]"
293+
cities_str = f"{cities}"
306294
query = f"""
307295
SELECT h.*, geo.lat as lat, geo.lon as lon, ARRAY_AVG(ARRAY r.ratings.Overall FOR r IN h.reviews WHEN r.ratings.Overall IS NOT MISSING END) as avg_rating
308296
FROM `travel-sample`.inventory.hotel h
@@ -328,11 +316,8 @@ This function visualizes flight routes between airports using [Plotly](https://p
328316
def plot_airports_and_routes(airports_df, routes_df):
329317
fig = go.Figure()
330318
# Create a dictionary mapping FAA codes to latitude and longitude for quick lookup
331-
airport_coords = {
332-
row["faa"]: (row["lat"], row["lon"])
333-
for _, row in airports_df.iterrows()
334-
if row["faa"] is not None # Ensure faa is not null
335-
}
319+
filtered_airports_df = airports_df.dropna(subset=["faa"]) # Remove rows where faa is NaN
320+
airport_coords = dict(zip(filtered_airports_df["faa"], zip(filtered_airports_df["lat"], filtered_airports_df["lon"])))
336321
lats = []
337322
lons = []
338323
# Iterate through routes to fetch airport coordinates and construct flight paths
@@ -367,7 +352,10 @@ def plot_airports_and_routes(airports_df, routes_df):
367352
fig.add_traces(airports_markers.data)
368353

369354
# Set map style and layout
355+
fig.update_geos(fitbounds="locations")
370356
fig.update_layout(
357+
map_zoom= 0.5, # Zoom level
358+
showlegend= False, # Hide legend
371359
mapbox_style="open-street-map",
372360
margin=dict(l=0, r=0, t=50, b=0), # Remove extra margins
373361
title="Airports and Flight Routes"
@@ -382,7 +370,9 @@ This function visualizes landmarks and nearby hotels on an interactive map using
382370

383371
```python
384372
def create_landmark_map(landmarks, hotels_near_landmark):
385-
fig = go.Figure()
373+
fig = go.Figure()
374+
centre = {"lat": 0, "lon": 0}
375+
num_points = 0
386376
# Plot hotels with color-coded markers based on distance
387377
for hotel in hotels_near_landmark:
388378
color = 'red' if hotel.get('distance') <= 3 else 'orange' if hotel.get('distance') <= 6 else 'gold'
@@ -397,6 +387,8 @@ def create_landmark_map(landmarks, hotels_near_landmark):
397387
hoverinfo='text',
398388
name=f'Hotel ({color})'
399389
))
390+
centre = {"lat": centre["lat"] + hotel.get('lat'), "lon": centre["lon"] + hotel.get('lon')}
391+
num_points += 1
400392

401393
# Plot landmarks as blue star markers
402394
for landmark in landmarks:
@@ -411,9 +403,17 @@ def create_landmark_map(landmarks, hotels_near_landmark):
411403
hoverinfo='text',
412404
name='Landmark'
413405
))
406+
centre = {"lat": centre["lat"] + landmark.get('lat', 0), "lon": centre["lon"] + landmark.get('lon', 0)}
407+
num_points += 1
408+
409+
if num_points > 0:
410+
centre = {"lat": centre["lat"] / num_points, "lon": centre["lon"] / num_points}
411+
fig.update_geos(fitbounds="locations")
414412

415413
# Configure map layout
416414
fig.update_layout(
415+
map_zoom=11,
416+
map_center=centre,
417417
mapbox_style='open-street-map',
418418
margin=dict(l=0, r=0, t=50, b=0),
419419
title='Landmarks and Hotels Nearby',
@@ -448,6 +448,10 @@ def create_hotel_map(hotels_df):
448448
if 'avg_rating' not in hotels_df.columns:
449449
hotels_df['avg_rating'] = np.nan # Add avg_rating column if it doesn't exist
450450
hotels_df['avg_rating'] = pd.to_numeric(hotels_df['avg_rating'], errors='coerce')
451+
centre = {
452+
"lat": hotels_df['lat'].mean(),
453+
"lon": hotels_df['lon'].mean()
454+
}
451455

452456
# Create a column for star ratings
453457
hotels_df['star_rating'] = hotels_df['avg_rating'].apply(lambda x: '' * int(round(x)) if not np.isnan(x) else 'No rating')
@@ -494,6 +498,8 @@ def create_hotel_map(hotels_df):
494498

495499
# Set up layout and color bar for ratings
496500
fig.update_layout(
501+
map_zoom=10,
502+
map_center=centre,
497503
mapbox_style="open-street-map",
498504
margin=dict(l=0, r=0, t=50, b=0),
499505
title="Hotels (colored by average rating)",
@@ -504,13 +510,6 @@ def create_hotel_map(hotels_df):
504510
)
505511
)
506512

507-
fig.update_layout(
508-
mapbox_style="open-street-map",
509-
margin=dict(l=0, r=0, t=50, b=0),
510-
title="Hotels (colored by average rating)",
511-
coloraxis_colorbar_title="Avg Rating"
512-
)
513-
514513
st.plotly_chart(fig, use_container_width=True)
515514
```
516515

@@ -593,8 +592,8 @@ def tab3_visual():
593592
# Retrieve the list of all available cities from the database
594593
all_cities = get_all_cities(connection)["city"].tolist()
595594

596-
# Allow users to select multiple cities; defaults to Newport, Birmingham, and London
597-
cities = st.multiselect("Select cities", all_cities, default=["Newport", "Birmingham", "London"])
595+
# Allow users to select multiple cities; defaults to London
596+
cities = st.multiselect("Select cities", all_cities, default=["London"])
598597

599598
# Fetch hotels based on the selected cities
600599
hotels = get_all_hotels(connection, cities)

0 commit comments

Comments
 (0)