如何使用flask将模型部署为服务
作者:yxs 时间:2021-11-11 06:02:48
目录
1. 加载保存好的模型
2. 使用flask起服务
3. 发送请求并得到结果
4. 效果呈现
1. 加载保存好的模型
为了方便起见,这里我们就使用简单的分词模型,相关代码如下:model.py
import jieba
class JiebaModel:
def load_model(self):
self.jieba_model = jieba.lcut
def generate_result(self, text):
return self.jieba_model(text, cut_all=False)
说明:在load_model方法中加载保存好的模型,无论是sklearn、tensorflow还是pytorch的都可以在里面完成。在generate_result方法中定义处理输入后得到输出的逻辑,并返回结果。
2. 使用flask起服务
代码如下:test_flask.py
# -*-coding:utf-8-*-
from flask import Flask, request, Response, abort
from flask_cors import CORS
# from ast import literal_eval
import time
import sys
import json
import traceback
from model import JiebaModel
app = Flask(__name__)
CORS(app) # 允许所有路由上所有域使用CORS
@app.route("/", methods=['POST', 'GET'])
def inedx():
return '分词程序正在运行中'
@app.route("/split_words", methods=['POST', 'GET'])
def get_result():
if request.method == 'POST':
text = request.data.decode("utf-8")
else:
text = request.args['text']
try:
start = time.time()
print("用户输入",text)
res = jiebaModel.generate_result(text)
end = time.time()
print('分词耗时:', end-start)
print('分词结果:', res)
result = {'code':'200','msg':'响应成功','data':res}
except Exception as e:
print(e)
result_error = {'errcode': -1}
result = json.dumps(result_error, indent=4, ensure_ascii=False)
# 这里用于捕获更详细的异常信息
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
# 提前退出请求
abort(Response("Failed!\n" + '\n\r\n'.join('' + line for line in lines)))
return Response(str(result), mimetype='application/json')
if __name__ == "__main__":
jiebaModel = JiebaModel()
jiebaModel.load_model()
app.run(host='0.0.0.0', port=1314, threaded=False)
说明:我们定义了一个get_result()函数,对应的请求是ip:port/split_words。 首先我们根据请求是get请求还是post请求获取数据,然后使用模型根据输入数据得到输出结果,并返回响应给请求。如果遇到异常,则进行相应的处理后并返回。在__main__中,我们引入了model.py的JiebaModel类,然后加载了模型,并在get_result()中调用。
3. 发送请求并得到结果
代码如下:test_request.py
import requests
def get_split_word_result(text):
res = requests.post('http://{}:{}/split_words'.format('本机ip', 1314), data=str(text).encode('utf-8'))
print(res.text)
get_split_word_result("我爱北京天安门")
说明:通过requests发送post请求,请求数据编码成utf-8的格式,最后得到响应,并利用.text得到结果。
4. 效果呈现
(1)运行test_flask.py
(2)运行test_request.py
并在起服务的位置看到:
来源:https://www.cnblogs.com/xiximayou/p/14763635.html
标签:flask,模型,部署服务
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Atom的python插件和常用插件说明
2022-11-29 00:46:08
js实时获得服务器上时间
2008-11-25 13:55:00
em与px的区别以及em特点和应用
2008-11-11 12:03:00
用asp实现读取文件的最后一行的代码
2011-03-08 10:55:00
python目标检测给图画框,bbox画到图上并保存案例
2023-03-07 07:47:52
三个动画函数,透明度渐变、位置移动、尺寸变化javascript源码
2010-03-28 13:23:00
谈谈Python进行验证码识别的一些想法
2022-09-19 12:50:53
![](https://img.aspxhome.com/file/2023/5/68955_0s.png)
GOLANG版的冒泡排序和快速排序分享
2023-07-05 05:31:09
Python statistics模块示例详解
2023-01-27 11:49:47
python中get和post有什么区别
2022-04-17 16:45:15
SQL Server 2005中的CLR集成
2009-03-10 15:07:00
Python理解递归的方法总结
2022-06-10 03:31:08
python实现有效的括号判断实例代码
2023-11-24 14:40:34
class和id命名探讨
2007-10-16 17:55:00
laravel学习教程之存取器
2023-06-07 20:01:12
PHP中error_reporting()函数的用法(修改PHP屏蔽错误)
2023-11-20 01:08:17
Goland激活码破解永久版及安装详细教程(亲测可以)
2023-06-18 14:30:43
![](https://img.aspxhome.com/file/2023/7/86287_0s.png)
Oracle CBO 的 _sort_elimination_cost_ratio 参数
2008-07-22 12:24:00
Pycharm2020.1安装中文语言插件的详细教程(不需要汉化)
2022-10-16 00:45:24
![](https://img.aspxhome.com/file/2023/9/81439_0s.jpg)
Python学习之字符串常用方法总结
2021-12-19 02:19:46
![](https://img.aspxhome.com/file/2023/1/67781_0s.png)