现有基于 Node.js 的项目,但须要整合 Data Science 同事的基于 python(jupyter) 的代码部分,以实现额外的数据分析功能。因而设想实现一个 microservices。下面介绍一些库的使用方法、本身写的 demo和遇到的坑,方便之后查阅。html
第一步,是想办法把 jupyter 文件当成一个 http server 启动,以即可以接受来自任何异构项目的调用。这里能够用到jupyter_kernel_gateway
的 notebook-http
功能。python
官方文档:https://jupyter-kernel-gateway.readthedocs.io/en/latest/http-mode.htmlgit
pip install jupyter_kernel_gateway
github
jupyter kernelgateway --KernelGatewayApp.api='kernel_gateway.notebook_http' --KernelGatewayApp.seed_uri='/Users/xjnotxj/Program/PythonProject/main.ipynb'
web
seed_uri
除了是本地路径,也能够是个urlhttp://localhost:8890/notebooks/main.ipynb
docker
import json
# imitate REQUEST args (调试时候用,平时请忽略) # REQUEST = json.dumps({'body': {'age': ['181']}, 'args': {'sex': ['male'], 'location': ['shanghai']}, 'path': {'name': 'colin'}, 'headers': {'Content-Type': 'multipart/form-data; boundary=--------------------------149817035181009685206727', 'Cache-Control': 'no-cache', 'Postman-Token': '96c484cb-8709-4a42-9e12-3aaf18392c92', 'User-Agent': 'PostmanRuntime/7.6.0', 'Accept': '*/*', 'Host': 'localhost:8888', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '161', 'Connection': 'keep-alive'}})
用注释定义路由:# POST /post/:name
(能够多个 cell 一块儿用),请求体自动绑定在 req
对象上:json
# POST /post/:name req = json.loads(REQUEST) # defined return vars return_status = 200 return_code = 0 return_message = '' return_data = {}
这里定义了一个检查 req 参数的 function,由于 jupyter_kernel_gateway 不支持 return 或者 exit 退出当前 request,仍是会继续日后执行,致使多个输出干扰最终 response 结果。因此我这边代码逻辑写的不简洁,若是有知道改进的朋友能够告诉我。api
# POST /post/:name def checkReqValid(req): global return_code global return_message # age if 100 <= req["age"] or req["age"] < 0: return_code = -2 return_message = "'age' is out of range" return True return False
实现 controller 部分:数组
# POST /post/:name try : name = req['path']['name'] age = int(req['body']['age'][0]) sex = req['args']['sex'][0] location = req['args']['location'][0] if checkReqValid({"name":name, "age":age, "sex":sex, "location":location}) == True: pass else : # dosomething…… return_data = { "name":name, "age":age, "sex":sex, "location":location, "req":req } except KeyError: # check has field is empty return_code = -1 return_message = "some field is empty" finally: # return data print(json.dumps({ "code":return_code, "message":return_message, "data":return_data }))
用 # ResponseInfo POST /post/:name
定义输出响应头,用 print
写入stdout 的方式来响应请求:网络
# ResponseInfo POST /post/:name print(json.dumps({ "headers" : { "Content-Type" : "application/json" }, "status" : return_status }))
当我访问localhost:8888/post/colin?sex=male&location=shanghai
且body体为 age:18
时,返回值为:
{ "code": 0, "message": "", "data": { "name": "colin", "age": 18, "sex": "male", "location": "shanghai", "req": { "body": { "age": [ "18" ] }, "args": { "sex": [ "male" ], "location": [ "shanghai" ] }, "path": { "name": "colin" }, "headers": { "Content-Type": "multipart/form-data; boundary=--------------------------981201125716045634129372", "Cache-Control": "no-cache", "Postman-Token": "ec0f5364-b0ea-4828-b987-c12f15573296", "User-Agent": "PostmanRuntime/7.6.0", "Accept": "*/*", "Host": "localhost:8888", "Accept-Encoding": "gzip, deflate", "Content-Length": "160", "Connection": "keep-alive" } } } }
关于响应码:
默认下为
200 OK
(且Content-Type: text/plain
)若是发生运行错误,则返回
500 Internal Server Error
若是没有找到路由,则返回
404 Not Found
若是找到路由可是 get/post 等这类请求方法仍是没匹配上,则返回
405 Not Supported
✘ xjnotxj@jiangchengzhideMacBook-Pro ~/Program/PythonProject jupyter kernelgateway --KernelGatewayApp.api='kernel_gateway.notebook_http' --KernelGatewayApp.seed_uri='/Users/xjnotxj/Program/PythonProject/tuo.ipynb' [KernelGatewayApp] Kernel started: bb13bcd6-514f-4682-b627-e6809cbb13ac Traceback (most recent call last): File "/anaconda3/bin/jupyter-kernelgateway", line 11, in <module> sys.exit(launch_instance()) File "/anaconda3/lib/python3.7/site-packages/jupyter_core/application.py", line 266, in launch_instance return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs) File "/anaconda3/lib/python3.7/site-packages/traitlets/config/application.py", line 657, in launch_instance app.initialize(argv) File "/anaconda3/lib/python3.7/site-packages/kernel_gateway/gatewayapp.py", line 382, in initialize self.init_webapp() File "/anaconda3/lib/python3.7/site-packages/kernel_gateway/gatewayapp.py", line 449, in init_webapp handlers = self.personality.create_request_handlers() File "/anaconda3/lib/python3.7/site-packages/kernel_gateway/notebook_http/__init__.py", line 112, in create_request_handlers raise RuntimeError('No endpoints were discovered. Check your notebook to make sure your cells are annotated correctly.') RuntimeError: No endpoints were discovered. Check your notebook to make sure your cells are annotated correctly. ✘ xjnotxj@jiangchengzhideMacBook-Pro ~/Program/PythonProject [IPKernelApp] WARNING | Parent appears to have exited, shutting down.
args
和body
体里的参数值是一个长度为1的数组# 注意取法 sex = req['args']['sex'][0]
第二步,就是用相似胶水的东西,把不一样的 Data Science 处理脚本,粘连起来,依次调用。
为何要使用papermill
,而不是直接调用脚本?
(1)规范了调用jurpyter文件和传参的模式
(2)执行jurpyter文件后能够生成 out 文件,方便回溯
(3)上下文变量按照每个jurpyter文件划分区域去存储,互不干扰
https://github.com/nteract/papermill
pip install papermill
a.ipynb
import papermill as pm for i, item in enumerate(data): data[i] = item * multiple pm.record("data", data) print(data)
main.ipynb
data=[1,2,3] data
# 也能够经过命令行运行,详细看文档 pm.execute_notebook( 'a.ipynb', 'a_out.ipynb', parameters = dict(data=data,multiple=3) )
Papermill 支持输入和输出路径有如下几种类型:
(1)本地文件系统: local
(2)HTTP,HTTPS协议: http://, https://
(3)亚马逊网络服务:AWS S3 s3://
(4)Azure:Azure DataLake Store,Azure Blob Store adl://, abs://
(5)Google Cloud:Google云端存储 gs://
执行main.ipynb
后:
一、会生成a_out.ipynb
新文件(见下文的(3))
二、有绑定在a_out.ipynb
上的上下文变量:
re = pm.read_notebook('a_out.ipynb').dataframe re
name | value | type | filename | |
---|---|---|---|---|
0 | data | [1, 2, 3] | parameter | a_out.ipynb |
1 | multiple | 3 | parameter | a_out.ipynb |
2 | data | [3, 6, 9] | record | a_out.ipynb |
获取参数稍微有一些繁琐,我这里封装了个 function:
# getNotebookData args # [filename] .ipynb的文件路径 # [field] 取值变量 # [default_value] 默认返回值(default:None) # [_type] 'parameter'|'record'(default) def getPMNotebookData(filename, field ,default_value = None,_type='record'): result = default_value try: re = pm.read_notebook(filename).dataframe result = re[re['name']==field][re['type']==_type]["value"].values[0] except: pass finally: return result data = getPMNotebookData('a_out.ipynb', 'data', 0) data # [3, 6, 9]
a_out.ipynb
生成的这个新文件,会多出两块内容:
一、在全部 cell 的最开头,会自动插入新的 cell,里面有咱们传入的参数
# Parameters data = [1, 2, 3] multiple = 3
二、cell 对应的 out 信息
[3, 6, 9]
会报错:
TypeError: Object of type DataFrame is not JSON serializable
解决办法:
一、序列化 Dataframe
Dataframe提供了两种序列化的方式,df.to_json()
或 df.to_csv()
,解析或者详细的用法请看:https://github.com/nteract/papermill/issues/215
缺点:
在序列化的过程当中,Dataframe 每列的数据类型会发生丢失,从新读取后需从新指定。
二、不经过 papermill 的传参机制去传输 Dataframe,而是经过 csv 中间文件承接 【推荐】
第三步,就是用 docker
,封装设计好的 microservices,以便部署。
待写……