• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何使用flask将模型部署为服务

python 搞代码 4年前 (2022-01-09) 37次浏览 已收录 0个评论

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, <em style="color:transparent">本文来源gao.dai.ma.com搞@代*码#网</em>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

并在起服务的位置看到:

以上就是如何使用flask将模型部署为服务的详细内容,更多关于用flask将模型部署为服务的资料请关注搞代码其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何使用flask将模型部署为服务

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址