我正在使用一个R脚本来查询一个API,处理数据,然后在闪亮的服务器上运行它。基本上有一个输入字段,然后它查询该用户名。然而,我想从一个discord机器人上做这件事。所以我想知道是否有办法监听www.example.comendpoint,然后使用这个端点的输入进行查询?
解决方案是使用plumber包。这基本上是为你的脚本创建一个端点。一个例子。
# plumber.R
#* Echo back the input
#* @param msg The message to echo
#* @get /echo
function(msg=""){
list(msg = paste0("The message is: '", msg, "'"))
}
然后你把它保存为一个R脚本,然后使用下面的内容。
library(plumber)
r <- plumb("plumber.R") # Where 'plumber.R' is the location of the file shown above
r$run(port=8000)
我在Ubuntu服务器上运行这个脚本 下面的代码会启动服务 在这种情况下,你不需要上面的行,只需要plumber.R文件,因为下面的代码在本质上是一样的。
sudo nano /etc/systemd/system/plumber-api.service
文件的内容应该是:
[Unit]
Description=Plumber API
# After=postgresql
# (or mariadb, mysql, etc if you use a DB with Plumber, otherwise leave this commented)
[Service]
ExecStart=/usr/bin/Rscript -e "api <- plumber::plumb('/your-dir/your-api-script.R'); api$run(port=8080, host='0.0.0.0')"
Restart=on-abnormal
WorkingDirectory=/your-dir/
[Install]
WantedBy=multi-user.target
https://www.rplumber.io/docs/hosting.html
sudo systemctl start plumber-api # starts the service
plumber软件包的详细信息 此处