适用于python的简易服务框架FLASK,flask也能支撑复杂业务,使用简便,我个人一般用其搭建简易服务,整理部分常用功能作为笔记。
导入包
import json as js
from flask import Flask, request
from flask import jsonify
import _thread # 非必须
基本设置
# 以当前文件为app的根
app = Flask(__name__)
# 类似json中的ensure_ascii=True,可以直接传输中文字符,不会变为字节码
app.config['JSON_AS_ASCII'] = True
健康服务检查
# 等同于本机ip后拼接'/health' -- http://localhost/health
@app.route('/health', methods=['GET', 'POST']) # 可以指定request的请求方式
def health():
return jsonify('OK!')
模型训练服务
# 以模型训练为例说明不同请求方式的运用和线程的作用
@app.route('/train', methods=['POST']) # 服务名字不必与下面的函数名一致
def model_train():
response = {'status': True, 'message': 'model start train...'}
if request.method == 'GET':
return jsonify('Wrong request type, only support post!')
elif request.method == 'POST':
# data = request.json # 数据可以为json格式传入也可以是文件
data = request.form
if not data:
response['message'] = 'data missed!'
response['status'] = False
else:
app_id = data.get('engineName', None)
url = data.get('response_url', None) # 回调函数,训练完成进行通知
if not (app_id and url):
response['message'] = 'can not find tenantId or app_id or response_url!'
response['status'] = False
else:
# 写入数据文件
task = request.files['file'] # 'file' -- form中的文件关键字
# 文件名
pic_name = 'task.xlsx'
# 文件写入磁盘
file_path = get_save_path(pic_name, app_id)
task.save(file_path)
# 开启线程训练模型,避免等待
_thread.start_new_thread(server_train, (app_id, url))
return jsonify(response) # 返回信息,模型开始训练