Reputation: 378
I am developing a shiny app which is deployed on a shiny server via a virtual machine. It is an exploratory data analytics app. The data is retrieved from a database via ODBC, which I use the RODBC
library for.
I would like the app to capable of running concurrent sessions and users (which is part of the point of a shiny app anyway) and I am new to this sort of deployment. The process of retrieving the data and wrangling it takes around 2 minutes. Here are two approaches that I have taken:-
First approach: data retrieval outside the server code
library(shiny)
library(DT)
library(RODBC)
library(dplyr)
#creating the driver connection variable
conn<-odbcConnect("<name of ODBC driver that I am using>")
#the sql query for pulling the data from the database
sql<- "SELECT * FROM <name of database>"
#retrieving and creating the dataframe
df<-sqlQuery(conn,sql)
#data wrangling sequence takes place
df%>%
...
...
...
ui<-fluidPage(
#rest of ui
...
)
server<-function(input, output,session){
#rest of server
...
}
shinyApp(ui,server)
This works locally, but on the server the issue with this approach is that it times out and then the browser page crashes.
Second approach: data retrieval inside the server code
ui<-fluidPage(
#rest of ui
...
)
server<-function(input, output,session){
# have the data retrieval process in the server
#creating the driver connection variable
conn<-odbcConnect("<name of ODBC driver that I am using>")
#the sql query for pulling the data from the database
sql<- "SELECT * FROM <name of database>"
#retrieving and creating the dataframe
df<-sqlQuery(conn,sql)
#data wrangling sequence takes place
df%>%
...
...
...
#rest of server
...
}
shinyApp(ui,server)
The issue here is that the data retrieval process begins again for each time the app is accessed by a new user. This is sub-optimal as it makes it slow and means it cannot be readily used.
My desired outcome would be that the data is retrieved once (as a static dataset) and then after, each time the app is accessed by a new user (or a new session is started), the data is ready to be analysed.
This is the first app I have deployed on a server so I need some pointers. What do I need to do in order to have the data called once and then make it ready for users as soon as the app is accessed by a new user?
Many thanks :)
Upvotes: 0
Views: 1457
Reputation: 5677
You can retrieve the data inside the global.R
file. All the objects created inside global.R
will be available for all the sessions of your app.
Here is an explanation of the Scoping rules for Shiny apps.
Another solution, since your data seems to be the same all the time, is to manually retrieve the data and save it in a local file. Then just load the data inside the server
from the local file, this will be faster than accessing the DB.
Upvotes: 1