是否可以在 openCPU 中控制 HTTP 响应行为?
Is it possible to control the HTTP response behavior in openCPU?
根据 the openCPU documentation,有一些默认的 HTTP 状态代码和 return 类型用于一些情况。例如,当 R 引发错误时,openCPU returns code 400
with a response type of text/plain
.
虽然我相信应该可以控制这些东西,但是否可以直接从 R 自定义这些东西?例如,如果我想 return JSON 用于我的 R 函数中的特定错误,状态代码为 503 怎么办?
您可以通过分叉 opencpu 或通过本地副本来更改其 R 包行为,即不确定包是否允许此功能,但响应已在 res.R
中配置
例如上面 link 中的此方法使用 400
作为错误。
error <- function(msg, status=400){
setbody(msg);
finish(status);
}
如果我可以在不更改包代码的情况下确认这是可用的,我将更新答案。
更新 17-04-2021
您可以编写您的服务 html 即 index.html,它使用 opencpu.js
从您的应用程序调用相应的 R 函数,可以请求 return 类型json
在 opencpu.js
通话中。在 R 函数中,您可以 tryCatch()
错误将适当的错误代码作为 json 参数发送。
例如在 stock example app you can see the file stock.js 中调用 R
文件夹中的函数,即
//this function gets a list of stocks to populate the tree panel
function loadtree(){
var req = ocpu.rpc("listbyindustry", {}, function(data){
Ext.getCmp("tree-panel").getStore().setProxy({
type : "memory",
data : data,
reader : {
type: "json"
}
});
Ext.getCmp("tree-panel").getStore().load();
}).fail(function(){
alert("Failed to load stocks: " + req.responseText);
});
}
对应的被调用的R代码在listbyindustry.R,里面可以tryCatch()
发送自定义json
.
根据 the openCPU documentation,有一些默认的 HTTP 状态代码和 return 类型用于一些情况。例如,当 R 引发错误时,openCPU returns code 400
with a response type of text/plain
.
虽然我相信应该可以控制这些东西,但是否可以直接从 R 自定义这些东西?例如,如果我想 return JSON 用于我的 R 函数中的特定错误,状态代码为 503 怎么办?
您可以通过分叉 opencpu 或通过本地副本来更改其 R 包行为,即不确定包是否允许此功能,但响应已在 res.R
中配置例如上面 link 中的此方法使用 400
作为错误。
error <- function(msg, status=400){
setbody(msg);
finish(status);
}
如果我可以在不更改包代码的情况下确认这是可用的,我将更新答案。
更新 17-04-2021
您可以编写您的服务 html 即 index.html,它使用 opencpu.js
从您的应用程序调用相应的 R 函数,可以请求 return 类型json
在 opencpu.js
通话中。在 R 函数中,您可以 tryCatch()
错误将适当的错误代码作为 json 参数发送。
例如在 stock example app you can see the file stock.js 中调用 R
文件夹中的函数,即
//this function gets a list of stocks to populate the tree panel
function loadtree(){
var req = ocpu.rpc("listbyindustry", {}, function(data){
Ext.getCmp("tree-panel").getStore().setProxy({
type : "memory",
data : data,
reader : {
type: "json"
}
});
Ext.getCmp("tree-panel").getStore().load();
}).fail(function(){
alert("Failed to load stocks: " + req.responseText);
});
}
对应的被调用的R代码在listbyindustry.R,里面可以tryCatch()
发送自定义json
.