flask模型部署教程

搭建python flask服务的步骤

1、安装相关的包

具体参考https://blog.csdn.net/weixin_42126327/article/details/127642279

1、安装conda环境和相关包

# 一、安装conda
# 1、首先,前往Anaconda官网(https://www.anaconda.com/products/individual)下载适合您的Linux版本的Anaconda安装文件。

# 2、下载Anaconda安装文件
wget https://repo.anaconda.com/archive/Anaconda3-2023.07-2-Linux-x86_64.sh
# 3、安装conda
bash Anaconda3-2023.07-2-Linux-x86_64.sh

# 4、conda --version
如果输出了Anaconda的版本号,则安装成功。

## 二、创建canda的虚拟开发环境 py36

# 1、创建canda的虚拟开发环境 py36
conda create --name py36 python=3.6

# 2、进入虚拟开发环境 
conda activate py36

# 3、退出虚拟环境
conda deactivate

## 三、安装flask相关的包
conda install flask
conda install scikit-learn

2、搭建flask服务代码

1、训练模型并保存模型

model.py


from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import pickle

# 加载iris数据集,并进行最简单的训练过程,可以自行扩展
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
classifier = RandomForestClassifier()
classifier.fit(X_train, y_train)
print(classifier)
 将模型保存为pkl格式,准备应用层调用
pickle.dump(classifier, open("./model.pkl", "wb"))

2、启动flask服务

app_demo.py


import numpy as np
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import pickle


app = Flask(__name__,template_folder='../templates')

model = pickle.load(open('model.pkl', 'rb'))
@app.route('/')
def home():
    return render_template('index.html')


@app.route('/results', methods=['POST'])
def results():
    data = request.get_json(force=True)
    print(data)
    prediction = model.predict([np.array(list(data.values()))])
    # 将预测结果放在字典中
    output = {'prediction': int(prediction[0])}
    # 将字典转换为 JSON 格式并返回
    return jsonify(output)
if __name__ == "__main__":
    app.run(debug=True)    
    

3、调用flask服务的客户端代码

request_demo.py python客服端代码


import requests
url = 'http://localhost:5000/results'
r = requests.post(url,json={'Sepal_Length':5,'Sepal_Width':2, 'Petal_Length':4, 'Petal_Width':2})
print(r.json())

FlaskClient.scala scala客户端代码

package com.demo

import java.net.URL

import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClientBuilder
import org.json4s._
import org.json.JSONObject
import org.apache.http.util.EntityUtils
import org.json4s.jackson.JsonMethods.parse

object FlaskClient {
  implicit val formats = DefaultFormats

  def main(args: Array[String]): Unit = {
    val url = new URL("http://localhost:5000/results")
    // 构造JSON对象
    val data = new JSONObject()
    data.put("feature1", 1)
    data.put("feature2", 2)
    data.put("feature3", 3)
    data.put("feature4", 4)

    // 将JSON对象转换为字符串
    val json = data.toString()
    val post = new HttpPost(url.toURI)
    post.setEntity(new StringEntity(json))
    post.setHeader("Content-type", "application/json")
    val client = HttpClientBuilder.create.build
    val response = client.execute(post)

    val entity = response.getEntity
    val result = EntityUtils.toString(entity)
    val prediction = (parse(result) \ "prediction").extract[Int]

    println(prediction)
    
  }
}


http客户端代码 templates/index.html






    
    ML API







3、flask服务的运行

1、调试环境


# 1、启动flask服务
python app_demo.py
# 2、客户端请求flask服务
# 2.1 python客户端
python request_demo.py 

# 2.2 scala 客户端
 java -cp target/xx-2.0.0-SNAPSHOT-jar-with-dependencies.jar com.xx.FlaskClient

# 2.3 http客户端
http://127.0.0.1:5000/predict 

2、生产环境部署

uWSGI:uWSGI是一个高性能的WSGI服务器,支持多种编程语言和应用程序框架,包括Flask。可以使用uWSGI来部署Flask服务
uwsgi安装

conda install uwsgi --no-deps # 使用--no-deps选项:这将跳过依赖项

部署 参考:https://juejin.cn/post/7014036187937505317

配置文件uwsgi.ini 文件

`
 [uwsgi]
 http = 127.0.0.1:5000
 wsgi-file = app_demo.py
 callable = app
 
 `

准备好配置文件后

# 启动uwsgi服务
uwsgi --ini uwsgi.ini
# 停止uwsgi服务
uwsgi --stop uwsgi.pid
# 重启uwsgi服务
uwsgi --reload uwsgi.pid

你可能感兴趣的:(python,算法,flask,python,后端)