我偶然发现了一个很棒的开源项目 openCPU.org,我对这个项目感到非常兴奋。作为一名试图创建一个网站来托管我的工作的研究科学家,我最希望能够在云上运行 R 以让我的脚本实时运行并显示在我的网页上。非常感谢 Jeroen 促成了这个项目。
有了这个,我的问题。
我到底如何与 openCPU 交互?
我可以将示例函数放入“运行一些代码”中:
http://public.opencpu.org/userapps/opencpu/opencpu.demo/runcode/
并检索我的代码的 PNG 图像,这很棒!
但是如何在我自己的网页中或通过 URL 执行此操作?
我可以从此页面获取原始代码上传的对象,例如:“x3ce3bf3e33”
如果是类似的函数:
myfun <-function(){
x = seq(1,6.28)
y = cos(x)
p = plot(x,y)
print(p)
# also tried return(p)
}
我不应该可以通过以下方式调用它:
http://public.opencpu.org/R/tmp/x3ce3bf3e33/png
输入变量呢?例如:
myfun <-function(foo){
x = seq(1,foo)
y = cos(x)
p = plot(x,y)
print(p)
}
我觉得也许我缺少一些东西。如何使用 url 指定“GET”或“POST”?
编辑
好的,为了响应下面的@Jeroen,我需要使用 POST 和 GET 和 API。现在我的问题延伸到以下问题,即让 PHP 与它正确交互。
说我有代码:
<?php
$foo = 'bar';
$options = array(
'method' => 'POST',
'foo' => $foo,
);
$url = "http://public.opencpu.org/R/tmp/x0188b9b9ce/save";
$result = drupal_http_request($url,$options); // drupal function
?>
然后我如何访问 $result 中传回的内容?我正在寻找一张图表。它看起来像这样:
{
"object" : null,
"graphs" : [
"x2acba9501a"
],
"files" : {}
}
下一步将是获取图像,类似于:
$newurl = "http://public.opencpu.org/R/tmp/".$result["graph"]."/png";
$image = drupal_http_request($newurl);
echo $image;
但我不知道如何访问 $result 的各个元素?
编辑#2
好的,伙计们,我已经完成了这项工作,这要归功于下面的答案和其他多个帮助会话,以及很多我的头撞在显示器上。
我们开始了,用 cURL 完成
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://public.opencpu.org/R/tmp/x0188b9b9ce/save');
curl_setopt($ch, CURLOPT_POST, 1); // Method is "POST"
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Returns the curl_exec string, rather than just Logical value
$result = curl_exec($ch);
curl_close($ch);
$new = json_decode($result,true); // $result is in 'json' format, decode it
$get = $new['graphs'][0]; // the 'hashkey for the image, "x2acba9501a" above
$img = 'http://public.opencpu.org/R/tmp/'.$get.'/png'; // link to the png image
echo <<<END // use this to display an image from the url
<a href="$img">
<img src="$img">
</a>
END
?>