需求:将jupyter notebook中打印的结果传到自己的tornado服务端,在tornado服务端写sql语句将jupyter notebook前端页面传递过来的数据保存,方便显示到其他地方(我们需要二次开发jupyter notebook,将其结果作为一种使用jupyter的人的操作反馈显示在我们的网站后台)
1、jupyter页面采用修改源码的方式
在jupyter源码根目录下找到notebook/templates/notebook.html添加如下代码
window.onload=function () { //var temp_result = $("#notebook div[class ~='selected'] .output_wrapper .output .output_text pre").text()) var temp_result = $("#notebook .output_wrapper .output .output_text pre").text() console.log(temp_result) }
看是否能打印出东西了。
如果能打印,说明修改源码的方式已经正确。那么可以做接下来的操作。
2、添加ajax代码使用jsonp的方式做跨域请求
notebook/templates/notebook.html中添加ajax请求的代码,
直接上源码来如下:
<script> window.onload=function () { //temp.push($("#notebook div[class ~='selected'] .output_wrapper .output .output_text pre").text()) var temp_result = $("#notebook .output_wrapper .output .output_text pre").text() //console.log(temp_result) $.ajax({ url: 'http://127.0.0.1:9000/ajaxjupyter',//http://127.0.0.1:9000/ajaxjupyter?callbackfun=jsonpCallback&temp_result=temp_result type: 'get', dataType: 'jsonp', jsonp:"callbackfun",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback) jsonpCallback:"jsonpCallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,如果定义了就success:function(){}就失效 data: { temp_result:temp_result }, }); } function jsonpCallback(data) { console.log(data) } </script>
3、tornado服务端需要做接收和处理返回
class AjaxjupyterHandler(HomeHandler): def get(self): temp_result = self.get_argument("temp_result", "") callbackfun = self.get_argument("callbackfun", "") #接受callback的名字callbackfun=jsonpCallback res = dict() res["status"] = 0 res["info"] = "添加成功" res["temp_result"] = temp_result self.set_header("content-type", "application/json") data = json.dumps(res) self.write(''+callbackfun+'('+data+')')
4、简单版本
其实经过步骤1、2、3是比较完整的,前端定义好jsonp:"传给后台的名字"名字,jsonpCallback:"回调函数名字",前端写好回调函数function 回调函数名字(data){处理逻辑},后端接受jsonp参数名,也就是前后端只要约定好这个jsonp处定义的是什么就可以了。当然这些东西都有默认值,下面就是简单版,全部采用juqery ajax默认的来做
前端:
<script> window.onload=function () { var temp_result = $("#notebook .output_wrapper .output .output_text pre").text() //console.log(temp_result) $.ajax({ url: 'http://127.0.0.1:9000/ajaxjupyter', //http://127.0.0.1:9000/ajaxjupyter?callback=一串随机数就在不用关心是什么,这个随机数是用来调用success:function(){}的&temp_result=temp_result type: 'get', dataType: 'jsonp', data: { temp_result:temp_result }, success:function (data) { console.log(data) } }); } </script>后端:
class AjaxjupyterHandler(HomeHandler): def get(self): temp_result = self.get_argument("temp_result", "") callback_test = self.get_argument("callback", "") # 前端没定义jsonp的值,是默认的jsonp=callback,这里接收的参数叫callback就行,其值赋给callback_test是一串随机数 res = dict() res["status"] = 0 res["info"] = "添加成功" res["temp_result"] = temp_result self.set_header("content-type", "application/json") data = json.dumps(res) self.write(''+callback_test+'(' + data + ')')
完~