如何访问反应对象?闪亮的登录示例

如何解决如何访问反应对象?闪亮的登录示例

我在此link上找到了登录示例,但是我有一个问题:如何访问已登录的用户?我意识到此信息存储在名为auth的对象中,但是如何在不给出错误的情况下访问它?

# NOT RUN {
if (interactive()) {
  
  library(shiny)
  library(shinymanager)
  
  # data.frame with credentials info
  credentials <- data.frame(
    user = c("1","fanny","victor"),password = c("1","azerty","12345"),comment = c("1","alsace","auvergne"),stringsAsFactors = FALSE
  )
  
  # app
  ui <- fluidPage(
    
    # authentication module
    auth_ui(
      id = "auth",# add image on top ?
      tags_top = 
        tags$div(
          tags$h4("Demo",style = "align:center"),tags$img(
            src = "https://www.r-project.org/logo/Rlogo.png",width = 100
          )
        ),# add information on bottom ?
      tags_bottom = tags$div(
        tags$p(
          "For any question,please  contact ",tags$a(
            href = "mailto:someone@example.com?Subject=Shiny%20aManager",target="_top","administrator"
          )
        )
      ),# change auth ui background ?
      background  = "linear-gradient(rgba(0,255,0.5),rgba(255,0.5)),url('https://www.r-project.org/logo/Rlogo.png');"
    ),# result of authentication
    verbatimTextOutput(outputId = "res_auth"),# classic app
    headerPanel('Iris k-means clustering'),sidebarPanel(
      selectInput('xcol','X Variable',names(iris)),selectInput('ycol','Y Variable',names(iris),selected=names(iris)[[2]]),numericInput('clusters','Cluster count',3,min = 1,max = 9)
    ),mainPanel(
      plotOutput('plot1')
    )
  )
  
  server <- function(input,output,session) {
    
    # authentication module
    auth <- callModule(
      module = auth_server,id = "auth",check_credentials = check_credentials(credentials)
    )
    
    output$res_auth <- renderPrint({
      reactiveValuesToList(auth) ## <---- this line print which user is logged in

    })
    
    # classic app
    selectedData <- reactive({
      
      req(auth$result)  # <---- dependency on authentication result
      
      iris[,c(input$xcol,input$ycol)]
    })
    
    clusters <- reactive({
      kmeans(selectedData(),input$clusters)
    })
    
    output$plot1 <- renderPlot({
      palette(c("#E41A1C","#377EB8","#4DAF4A","#984EA3","#FF7F00","#FFFF33","#A65628","#F781BF","#999999"))
      
      par(mar = c(5.1,4.1,1))
      plot(selectedData(),col = clusters()$cluster,pch = 20,cex = 3)
      points(clusters()$centers,pch = 4,cex = 4,lwd = 4)
    })
  }
  
  shinyApp(ui,server)
  
}

如何访问auth $ user?下标越界错误正在发生,我想访问在应用程序内标记为“

我的个人情况:我正在尝试向MySQL数据库发送查询,如下所示:

  1. 尝试1(使用user_data())
user_data <- reactive({
    req(auth$result)
    auth$user
  })
connection<-reactivePoll( intervalMillis = 300,session,checkFunc = function(){
    storiesDb <- dbConnect(RMariaDB::MariaDB(),user='USER',password=localuserpassword,dbname='USER',host='localhost')
    querysel1=reactive({paste("SELECT COL1
                 FROM   TABLENAME
                 where id ='",user_data(),"' ",sep= ''
    )})
    rs = dbSendQuery(storiesDb,querysel1)
    
    dbFetch(rs) },valueFunc = function(){
      
      querysel1=reactive({paste("SELECT COL1
                 FROM   TABLENAME
                 where id ='",sep= ''
                      
      )}) 
      rs = dbSendQuery(storiesDb,querysel1)
      dbFetch(rs)
    }
  )

我尝试使用user_data(),并给出错误:“无法为签名”“ MariaDBConnection”,“ reactiveExpr””'”找到函数'dbSendQuery'的继承方法

  1. 尝试2(不使用user_data())
connection<-reactivePoll( intervalMillis = 300,auth$user,querysel1)

    dbFetch(rs) },valueFunc = function(){

      querysel1=reactive({paste("SELECT COL1
                 FROM   TABLENAME
                 where id ='",sep= ''

      )}) 
      rs = dbSendQuery(storiesDb,querysel1)
      dbFetch(rs)
    }
  )

我尝试使用auth $ user,并给出错误:“ as.vector(x,“ character”)错误:无法将类型'closure'强制转换为'character'类型的vector“

  1. 尝试3(在querysel1中不响应)
connection<-reactivePoll( intervalMillis = 300,host='localhost')
    querysel1=paste("SELECT COL1
                 FROM   TABLENAME
                 where id ='",sep= ''
    )
    rs = dbSendQuery(storiesDb,valueFunc = function(){

      querysel1=paste("SELECT COL1
                 FROM   TABLENAME
                 where id ='",sep= ''

      ) 
      rs = dbSendQuery(storiesDb,querysel1)
      dbFetch(rs)
    }
  )

我在querysel1中尝试了无反应式,并给出了空错误:“ Error:”

在我看来,所有这些错误都是由于服务器内部的反应对象而发生的。

解决方法

编辑

感谢提供reactivePoll的更多信息,我想我发现了问题:

这里的问题在于执行reactivePoll。启动应用程序时,reactivePoll已经开始执行,但是尚未登录任何用户。这意味着auth$user尚不存在(它是NULL),并且checkFunvalueFun中的代码无法处理。我提供了一个小示例(使用user = 1和password = 1)来说明它在原理上是可行的。只要auth$userNULL,我就确保不执行代码:

library(shiny)
library(shinymanager)

# data.frame with credentials info
credentials <- data.frame(
  user = c("1","fanny","victor"),password = c("1","azerty","12345"),comment = c("1","alsace","auvergne"),stringsAsFactors = FALSE
)

# app
ui <- fluidPage(
  
  # authentication module
  auth_ui(
    id = "auth",# add image on top ?
    tags_top = 
      tags$div(
        tags$h4("Demo",style = "align:center"),tags$img(
          src = "https://www.r-project.org/logo/Rlogo.png",width = 100
        )
      ),# add information on bottom ?
    tags_bottom = tags$div(
      tags$p(
        "For any question,please  contact ",tags$a(
          href = "mailto:someone@example.com?Subject=Shiny%20aManager",target="_top","administrator"
        )
      )
    ),# change auth ui background ?
    background  = "linear-gradient(rgba(0,255,0.5),rgba(255,0.5)),url('https://www.r-project.org/logo/Rlogo.png');"
  ),# result of authentication
  verbatimTextOutput(outputId = "res_auth"),# classic app
  headerPanel('Iris k-means clustering'),sidebarPanel(
    selectInput('xcol','X Variable',names(iris)),selectInput('ycol','Y Variable',names(iris),selected=names(iris)[[2]]),numericInput('clusters','Cluster count',3,min = 1,max = 9)
  ),mainPanel(
    plotOutput('plot1'),textOutput("user_name")
  )
)

server <- function(input,output,session) {
  
  # authentication module
  auth <- callModule(
    module = auth_server,id = "auth",check_credentials = check_credentials(credentials)
  )
  
  output$res_auth <- renderPrint({
    reactiveValuesToList(auth) ## <---- this line print which user is logged in
    
  })
  
  # the following line is just an example how to use auth$user in a different
  # reactive
  user_data <- reactive({
    auth$user
  })
  
  # call the new reactive in a render function
  output$user_name <- renderText({
    paste0("The user currently logged in is: ",user_data())
  })
  
  # classic app
  selectedData <- reactivePoll(intervalMillis = 1000,session,checkFunc = function() {
                             if (!is.null(auth$user) && auth$user == "1") {
                               rnorm(1)
                             } else {
                               1
                             }
                           },valueFunc = function() {
                             n_row <- sample(1:150,120)
                             iris[n_row,c(input$xcol,input$ycol)]
                           })
  
  clusters <- reactive({
    kmeans(selectedData(),input$clusters)
  })
  
  output$plot1 <- renderPlot({
    palette(c("#E41A1C","#377EB8","#4DAF4A","#984EA3","#FF7F00","#FFFF33","#A65628","#F781BF","#999999"))
    
    par(mar = c(5.1,4.1,1))
    plot(selectedData(),col = clusters()$cluster,pch = 20,cex = 3)
    points(clusters()$centers,pch = 4,cex = 4,lwd = 4)
  })
}

shinyApp(ui,server)

我不确定为什么,但是仅添加req(auth$user)在这里行不通。

您可以执行以下操作:

connection<-reactivePoll( intervalMillis = 300,checkFunc = function(){
                            if (!is.null(auth$user)) {
                              storiesDb <- dbConnect(RMariaDB::MariaDB(),user='USER',password=localuserpassword,dbname='USER',host='localhost')
                              querysel1=paste("SELECT COL1
                 FROM   TABLENAME
                 where id ='",auth$user,"' ",sep= ''
                              )
                              rs = dbSendQuery(storiesDb,querysel1)
                              
                              dbFetch(rs)
                            } else {
                              NULL
                            }
                          },valueFunc = function(){
                            if (!is.null(auth$user)) {
                              querysel1=paste("SELECT COL1
                 FROM   TABLENAME
                 where id ='",sep= ''
                                              
                              ) 
                              rs = dbSendQuery(storiesDb,querysel1)
                              dbFetch(rs)
                            } else {
                              NULL
                            }
                          }
)

在这里,只要NULL不存在,我就返回auth$user,您可以根据需要进行调整。


我的旧答案:

我不确定您的问题/错误到底发生在哪里。对我来说,您的示例有效。我添加了另一个示例,说明如何访问auth$user。由于它是响应式的,因此只能在响应式上下文中访问它。

library(shiny)
library(shinymanager)

# data.frame with credentials info
credentials <- data.frame(
  user = c("1",user_data())
  })
  
  # classic app
  selectedData <- reactive({
    
    req(auth$result)  # <---- dependency on authentication result
    
    iris[,input$ycol)]
  })
  
  clusters <- reactive({
    kmeans(selectedData(),server)
,

要详细说明我的评论,也许最好显示代码:

请在注释中查看哪些语句有效,哪些无效。我只是将用户victor与通行证12345一起使用,而没有检查它是否与其他凭据一起使用。

library(shiny)
library(shinymanager)

# data.frame with credentials info
credentials <- data.frame(
  user = c("1",mainPanel(
    plotOutput('plot1')
  )
)

server <- function(input,check_credentials = check_credentials(credentials)
  )
  
  output$res_auth <- renderPrint({
    # reactiveValuesToList(auth$user) ## <---- not working
    auth[["user"]] ## <----  working
    # auth$user ## <----  this works too 
    # reactiveValuesToList(auth)[["user"]] # <--- this works too 
    
  })
  
  # classic app
  selectedData <- reactive({
    
    req(auth$result)  # <---- dependency on authentication result
    
    iris[,server)

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-