Question: Python and Dash Framework Open the ModuleSixMilestone.ipynb file, which contains the starter code for the Grazioso Salvare dashboard. Upload this file into Apporto and

Python and Dash Framework

 

Open the ModuleSixMilestone.ipynb file, which contains the starter code for the Grazioso Salvare dashboard. Upload this file into Apporto and open it using the Jupyter Notebook application. Be sure to review all of the starter code that you have been given. Pay special attention to the import commands and the comments describing what each section of code does.
Update the code to an interactive data table on the dashboard which shows an unfiltered view of the Austin Animal Center Outcomes data set. To populate the data onto your table, you will utilize your previous CRUD Python module, from Project One, to run a "retrieve all" query and bring in the data from MongoDB. This data retrieval will serve to access the "model" portion of your MVC pattern: the MongoDB database. Be sure to hardcode in the username and password for the "aacuser" account.

Note: It may take a few minutes for the data table to fully render and display, depending on the speed of your internet connection.

Tip: Be sure to consider your client when creating the interactive data table. Consider optional features that will make the table easier to use, such as limiting the number of rows displayed, enabling pagination (advanced), enabling sorting, and so on. Review the Module Six resources on data tables to help you select and set up these features.
Add a geolocation chart that displays data from the interactive data table to your existing dashboard.
You are being given the function that sets up accessing the data for the geolocation chart and calls the Leaflet function: update_map:
 
You will need to structure this function into your dashboard code by putting the correct statements in the layout. These statements are important so that your layout has a place for the geolocation chart. Here is an example statement:
 
You will also need to add in the correct callback routines for the geolocation chart. These will look similar to the callback routines used for user authentication and your data table. Here is an example callback routine:
 
Finally, run the IPYNB file and take a screenshot of your dashboard as proof of this execution. Your screenshot should include 1) the interactive data table populated with the Austin Animal Center Outcomes data from MongoDB and 2) your geolocation chart showing the location of the first dog in the table. Additionally, your unique identifier (created in the Module Five assignment) should also be visible in the screenshot.
 

 

PY File (CrudModule.py) - No issues here

 

from pymongo import MongoClient
from bson.objectid import ObjectId

class AnimalShelter(object):
   """CRUD OPERATIONS for Animal Collection in MongoDB"""
   
   def __init__(self, user, password):
       #self.client = MongoClient('mongodb://localhost:53598')
       #self.client = MongoClient('mongodb://127.0.0.1:37300/?authSource=AAC&compressors=disabled&gssapiServiceName=mongodb' % (user, password))
       self.client = MongoClient('mongodb://%s:%s@localhost:53598/AAC' % (aacuser, UserCS340))
       self.database = self.client['AAC']
       print("Connected to Database")

 

from pymongo import MongoClient
from bson.objectid import ObjectId

class AnimalShelter(object):
   """CRUD OPERATIONS for Animal Collection in MongoDB"""
   
   def __init__(self, user, password):
       #self.client = MongoClient('mongodb://localhost:53598')
       #self.client = MongoClient('mongodb://127.0.0.1:37300/?authSource=AAC&compressors=disabled&gssapiServiceName=mongodb' % (user, password))
       self.client = MongoClient('mongodb://%s:%s@localhost:53598/AAC' % (aacuser, UserCS340))
       self.database = self.client['AAC']
       print("Connected to Database")

 

#Implement read in Crud
   def read(self, target):
       try:
           if target is not None:
               read_result = list(self.database.animals.find(target, {"_id": False}))
               return read_result
           else:
               raise Exception("Nothing to find. Target is empty.")
               return False
       except Exception as e:
           print("Exception has occured: ", e)

 

#U operation for update in CRUD
   def update(self, fromTarget, toTarget, count):
       if fromTarget is not None:
           if count == 1:
               update_result = self.database.animals.update(fromTarget, toTarget)
               #print("Matched Count: " + str(update_result.matched_count) + ", Modified Count: " + str(update_result.modified_count))
               #if update_result.modified_count == 1:
               print("Success!")
               print(update_result)
               return True
               
           elif count == 2:
               update_result = self.database.animals.update(fromTarget, toTarget)
               #print("Matched Count: " + str(update_result.matched_count) + ", Modified Count: " + str(update_result.modified_count))
               #if update_result.modified_count == update_result.matched_count:
               print("Success!")
               print(update_result)
               return True
               
           else:
               print("Count not recognized - try again.")
               return False
       else:
           #lets the user know there was a problem
           raise Exception("Nothing to update, because at least one of the target parameters is empty")
           return False

 

#D operation for delete in CRUD
   def deleteData(self, target, count):
       if target is not None:
           if count == 1:
               try:
                   delete_result = self.database.animals.delete_one(target)
                   #print("Deleted Count: " + str(delete_result.deleted_count))
                   print("Success!")
                   print(delete_result)
                   return True
               except Exception as e:
                   print("An exception has occurred: ", e)
           elif count == 2:
               try:
                   delete_result = self.database.animals.delete_many(target)
                   #print("Deleted Count: " + str(delete_result.deleted_count))
                   print("Success!")
                   print(delete_result)
                   return True
               except Exception as e:
                   print("An exception has occurred: ", e)
                   return False
           else:
               print("Count not recognized - try again.")
               return False
       else:
           #lets the user know there was a problem
           raise Exception("Nothing to delete, because the target parameter is empty")
           return False  

 

 

Dash Framwork File - Lots of issues here. I cannot figure it out

 

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
from pymongo import MongoClient
from bson.json_util import dumps
import base64

#### FIX ME #####
# change animal_shelter and AnimalShelter to match your CRUD Python module file name and class name
from CrudModule import AnimalShelter


###########################
# Data Manipulation / Model
###########################
# FIX ME update with your username and password and CRUD Python module name

username = "aacuser"
password = "UserCS340"
shelter = AnimalShelter(username, password)


# class read method must support return of cursor object and accept projection json input
df = pd.DataFrame.from_records(shelter.read({}))


#########################
# Dashboard Layout / View
#########################

app = JupyterDash('Domingo Polonia')

app.layout = html.Div([
   html.Div(id='hidden-div', style={'display':'none'}),
   html.Center(html.B(html.H1('Hello Domingo Polonia'))),
   html.Hr(),
   dash_table.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

   html.Div(className='row',
        style={'display' : 'flex'},
            children=[
       html.Div(
           #dcc.Graph(id='graph-id'),
           id='graph-id',
           className='col s12 m6',

           ),
       html.Div(
           id='map-id',
           className='col s12 m6',
           )
       ])
   )

#############################################
# Interaction Between Components / Controller
#############################################
#This callback will highlight a row on the data table when the user selects i..;@app.callback(
   Output('map-id', "children"),
   [Input('datatable-id', "derived_viewport_data")])

def update_styles(selected_columns):
   return [{
       'if': { 'column_id': i },
       'background_color': '#D2F3FF'
   } for i in s..;@app.callback(
   Output('map-id', "children"),
   [Input('datatable-id', "derived_viewport_data")])
   
def update_map(viewData):
       dff = pd.DataFrame.from_dict(viewData)
   # Austin TX is at [30.75,-97.48]
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=[30.75,-97.48], children=[
               dl.Tooltip(dff.iloc[0,4]),
               dl.Popup([
                   html.H1("Animal Name"),
                   html.P(dff.iloc[1,9])
               ])
           ])
       ])
   ]
   
#FIXME Add in the code for your geolocation chart
   

app

 

 

 

Requirements for assignment

@app.callback(
    Output('map-id', "children"),
    [Input('datatable-id', "derived_viewport_data")])
html.Div(
            id='map-id',
            className='col s12 m6',
            )
def update_map(viewData):
    dff = pd.DataFrame.from_dict(viewData)
    # Austin TX is at [30.75,-97.48]
    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=[30.75,-97.48], children=[
                dl.Tooltip(dff.iloc[0,4]),
                dl.Popup([
                    html.H1("Animal Name"),
                    html.P(dff.iloc[1,9])
                ])
            ])
        ])
    ]

Step by Step Solution

3.36 Rating (152 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Explanation of the Code 1 CRUD Python Module CrudModulepy Import Statements from pymongo import MongoClient imports the MongoClient class to connect to the MongoDB database from bsonobjectid import Ob... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!