繁体   English   中英

在 R 会话中访问本地提供的文件

[英]Access locally served files within an R session

语境

为了测试我正在编写的 R 包的 Web 功能,我尝试在本地使用httpuv包提供文件,以便我可以使用页面的离线副本运行测试。

问题

然而, curl似乎并不想与httpuv配合得httpuv ——特别是,当尝试使用curl读取托管文件时(例如,使用curl::curl()curl::curl_fetch_memory() ),请求挂起,如果没有手动中断,最终会超时。

最小的例子

# Serve a small page
server <- httpuv::startServer("0.0.0.0", port = 9359, app = list(
  call = function(req) {
    list(
      status = 200L,
      headers = list("Content-Type" = "text/html"),
      body = "Some content..."
    )
  }
))

# Attempt to retrieve content (this hangs)
page <- curl::curl_fetch_memory(url = "http://127.0.0.1:9359")

httpuv::stopServer(server)

现在的进展

服务器启动后,在终端运行curl -v 127.0.0.1:9359按预期返回内容。 此外,如果我打开 RStudio 的新实例并尝试在该新 R 会话中curl::curl_fetch_memory() (而旧会话仍处于打开状态),它将完美运行。

callr鼓舞,我一直在玩callr一段时间,想也许可以在某个后台进程中启动服务器,然后像往常一样继续。 不幸的是,到目前为止,我用这种方法还没有取得任何成功。

非常感谢任何见解或建议!

当你能回来回答你问的问题时,是不是一种很棒的感觉!

httpuv::startServer()文档:

startServer 绑定指定的端口并在后台运行的线程上侦听连接。 这个后台线程处理 I/O,当它接收到一个 HTTP 请求时,它会调度调用 app 中用户定义的 R 函数来处理请求。 这个调度是通过 later() 完成的。 当 R 调用堆栈为空时——换句话说,当交互式 R 会话在命令提示符下处于空闲状态时——R 将自动运行计划调用。 但是,如果调用堆栈不为空——如果 R 正在评估其他 R 代码——那么回调将不会执行,直到调用堆栈为空或 run_now() 函数被调用。 该函数告诉 R 执行任何由 later() 安排的回调。 service() 函数本质上是 run_now() 的包装器。

换句话说,如果我们想在收到请求后立即响应,我们必须使用httpuv::service()明确地这样做。 像下面这样的东西可以解决问题!

s <- callr::r_session$new()
on.exit(s$close())

s$call(function() {
  httpuv::startServer("0.0.0.0", port = 9359, app = list(
    call = function(req) {
      list(
        status = 200L,
        headers = list("Content-Type" = "text/html"),
        body = "Some content...")
      )
    }
  ))

  while (TRUE) httpuv::service()
})  

# Give the server a chance to start
Sys.sleep(3)
page <- curl_fetch_memory(url = "http://127.0.0.1:9359")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM