Jupyter Dashboard Water Rescue组件查询更新异常排查求助
水上救援犬筛选组件调试问题
我正在调试Jupyter Notebook中名为Water Rescue的组件,该组件需要筛选出符合水上救援犬标准的犬只(如Labrador Retriever Mix、Chesa Bay Retr Mix、Newfoundland Mix等),更新输出数据表并渲染对应品种占比的饼图。但点击该组件后,饼图仍显示原始数据表的品种占比,数据表也未按预期更新,怀疑update_dashboard函数中的MongoDB查询存在问题,相关代码如下:
ProjectTwoDashboard.ipynb
from jupyter_plotly_dash import JupyterDash import dash import dash_leaflet as dl import dash_core_components as dcc import dash_html_components as html import plotly.express as px import dash_table as dt from dash.dependencies import Input, Output, State import os import numpy as np import pandas as pd import base64 from pymongo import MongoClient from bson.json_util import dumps from IPython.display import Image #### FIX ME ##### # change animal_shelter and AnimalShelter to match your CRUD Python module file name and class name from animal_shelter import AnimalShelter ########################### # Data Manipulation / Model ########################### # FIX ME change for your username and password and CRUD Python module name username = "accuser" password = "Superman" shelter = AnimalShelter(username, password) # class read method must support return of cursor object df = pd.DataFrame.from_records(shelter.read({})) ######################### # Dashboard Layout / View ######################### app = JupyterDash('ProjectTwo') #FIX ME Add in Grazioso Salvare’s logo image_filename = 'Grazioso Salvare Logo.png' # replace with your own image encoded_image = base64.b64encode(open(image_filename, 'rb').read()) #FIX ME Place the HTML image tag in the line below into the app.layout code according to your design #FIX ME Also remember to include a unique identifier such as your name or date #html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode())) app.layout = html.Div([ html.Div(id='hidden-div', style={'display':'none'}), html.Center(html.Img(src='data.image/png;base64,{}'.format(encoded_image.decode()))), html.Center(html.B(html.H1('SNHU CS-340 Dashboard'))), html.Hr(), html.Div( #FIXME Add in code for the interactive filtering options. For example, Radio buttons, drop down, checkboxes, etc. dcc.RadioItems( id='filter-type', options=[ {'label': 'Water Rescue', 'value': 'WR'}, {'label': 'Mountain or Wilderness', 'value': 'MWR'}, {'label': 'Disaster or Individual Tracking', 'value': 'DIT'}, {'label': 'Reset', 'value': 'RESET'} ], value='RESET', labelStyle={'display':'inline-block'}) ), html.Hr(), dt.DataTable( id='datatable-id', columns=[ {"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns ], data=df.to_dict('records'), #FIXME: Set up the features for your interactive data table to make it user-friendly for your client #If you completed the Module Six Assignment, you can copy in the code you created here editable=False, filter_action="native", sort_action="native", sort_mode="multi", column_selectable=False, row_selectable=False, row_deletable=False, selected_columns=[], selected_rows=[], page_action="native", page_current=0, page_size=10, ), html.Br(), html.Hr(), #This sets up the dashboard so that your chart and your geolocation chart are side-by-side html.Div(className='row', style={'display' : 'flex'}, children=[ html.Div( id='graph-id', className='col s12 m6', ), html.Div( id='map-id', className='col s12 m6', ), html.H4("This is Vincent, computer science major") ]) ]) ############################################# # Interaction Between Components / Controller ############################################# @app.callback( [Output('datatable-id','data'), Output('datatable-id','columns')], [Input('filter-type', 'value')]) def update_dashboard(filter_type): ### FIX ME Add code to filter interactive data table with MongoDB queries if filter_type == 'WR': df = pd.DataFrame(list(shelter.read({'$and': [{'sex_upon_outcome': 'Intact Female'}, {'$or': [ {'breed': 'Laborador Retriever Mix'}, {'breed': 'Chesa Bay Retr Mix'}, {'breed': 'Newfoundland Mix'}, {'breed': 'Newfoundland/Laborador Retriever'}, {'breed': 'Newfoundland/Australian Cattle Dog'}, {'breed': 'Newfoundland/Great Pyrenees'} ]}, {'$and': [{'age_upon_outcome_in_weeks': {'$gte': 26}}, {'age_upon_outcome_in_weeks': {'$lte': 156}}] }] }))) elif filter_type == 'MWR': #Grazioso breeds and ages df = pd.DataFrame(list(shelter.read({'$and': [{'sex_upon_outcome': 'Intact Male'}, {'$or': [ {'breed': 'German Shepherd'}, {'breed': 'Alaskan Malamute'}, {'breed': 'Old English Sheepdog'}, {'breed': 'Rottweiler'}, {'breed': 'Siberian Husky'} ]}, {'$and': [{'age_upon_outcome_in_weeks': {'$gte': 26}}, {'age_upon_outcome_in_weeks': {'$lte': 156}}] }] }))) #adjusts the read request for the desired dog type and status elif filter_type == 'DRIT': #breeds and ages df = pd.DataFrame(list(shelter.read({'$and': [{'sex_upon_outcome': 'Intact Male'}, {'$or': [ {'breed': 'Doberman Pinscher'}, {'breed': 'German Shepherd'}, {'breed': 'Golden Retriever'}, {'breed': 'Bloodhound'}, {'breed': 'Rottweiler'} ]}, {'$and': [{'age_upon_outcome_in_weeks': {'$gte': 20}}, {'age_upon_outcome_in_weeks': {'$lte': 300}}] }] }))) #resets the search no filter elif filter_type == 'RESET': df = pd.DataFrame.from_records(shelter.read({})) columns=[{"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns] data=df.to_dict('records') return (data,columns) @app.callback( Output('datatable-id', 'style_data_conditional'), [Input('datatable-id', 'selected_columns')] ) def update_styles(selected_columns): return [{ 'if': { 'column_id': i }, 'background_color': '#D2F3FF' } for i in selected_columns] @app.callback( Output('graph-id', "children"), [Input('datatable-id', "derived_viewport_data")]) def update_graphs(viewData): ###FIX ME #### dff = pd.DataFrame.from_dict(viewData) names = dff['breed'].value_counts().keys().tolist() values = dff['breed'].value_counts().tolist() # add code for chart of your choice (e.g. pie chart) return [ dcc.Graph( figure = px.pie( data_frame = dff, values = values, names = names, color_discrete_sequence=px.colors.sequential.RdBu, width = 800, height = 500 ) ) ] @app.callback( Output('map-id', "children"), [Input('datatable-id', "derived_viewport_data"), Input('datatable-id', 'selected_rows'), Input('datatable-id', 'selected_columns')]) def update_map(viewData, selected_rows, selected_columns): #FIXME: Add in the code for your geolocation chart #If you completed the Module Six Assignment, you can copy in the code you created here. dff = pd.DataFrame.from_dict(viewData) if selected_rows == []: selected_rows = [0] # Austin TX is at [30.75, -97.48] if len(selected_rows) == 1: return [ dl.Map(style={'width':'1000px', 'height': '500px'}, center=[30.75,-97.48], zoom=10, children=[ dl.TileLayer(id="base-layer-id"), #marker with tool tip and popup dl.Marker(position=[(dff.iloc[selected_rows[0],13]), (dff.iloc[selected_rows[0],14])], children=[ dl.Tooltip(dff.iloc[selected_rows[0],4]), dl.Popup([ html.H4("Animal Name"), html.P(dff.iloc[selected_rows[0],9]), html.H4("Sex"), html.P(dff.iloc[selected_rows[0],12]), html.H4("Breed"), html.P(dff.iloc[selected_rows[0],4]), html.H4("Age"), html.P(dff.iloc[selected_rows[0],15]) ]) ]) ]) ] app
animal_shelter.py
from pymongo import MongoClient from bson.objectid import ObjectId from bson.json_util import dumps class AnimalShelter(object): """ CRUD operations for Animal collection in MongoDB """ def __init__(self,username,password): # Initializing the MongoClient. This helps to # access the MongoDB databases and collections. # init to connect to mongodb without authentication self.client = MongoClient('mongodb://localhost:55996') # init connect to mongodb with authentication #self.client = MongoClient('mongodb://%s:%s@localhost:55996/?authMechanism=DEFAULT&authSource=AAC'%(username, password)) self.database = self.client['AAC'] # Complete this create method to implement the C in CRUD. def create(self, data): if data is not None: self.database.animals.insert(data) # data should be dictionary return True # Tells whether the create function ran successfully else: raise Exception("Nothing to save ...") # Create method to implement the R in CRUD. def read(self, data): if data: cursor = self.database.animals.find(data, {'_id':False}) else: cursor = self.database.animals.find({}, {"_id": False}) return cursor # Update method to implement the U in CRUD. def update(self, data, new_values): updated_data = {"name":"Rhonda","age_upon_outcome":"2 years"} if self.database.animals.count(data): self.database.animals.update(data, new_values) cursor = self.database.animals.find(updated_data) json_data = dumps(cursor) return json_data else: raise Exception("Nothing to update ...") # Delete method to implement the D in CRUD def delete(self, data): result = self.database.animals.find_one_and_delete(data) # print the _id key only if the result is not None if("_id" in result): print("find_one_and_delete ID:",result["_id"]) else: print("Nothing to delete")
问题排查与修复方案
- 拼写错误导致查询无结果:Water Rescue查询中
Laborador Retriever Mix拼写错误,应改为Labrador Retriever Mix,同时Newfoundland/Laborador Retriever也需修正为Newfoundland/Labrador Retriever。 - 选项值不匹配:RadioItems中Disaster or Individual Tracking的value是
DIT,回调函数中判断的是DRIT,需将回调中的DRIT改为DIT。 - MongoDB连接未认证:若MongoDB实例需要认证,需取消
AnimalShelter类__init__方法中认证连接代码的注释,启用带用户名密码的连接。 - 图片URL格式错误:布局中图片src属性的
data.image/png;base64需改为data:image/png;base64,确保图片正常加载。 - 饼图数据处理优化:
update_graphs函数可简化,直接使用px.pie的names='breed'参数,无需手动统计数量,避免冗余代码。
内容的提问来源于stack exchange,提问作者FireMonkey
相关产品推荐
相关产品推荐

