搭建python flask服務(wù)的步驟
1、安裝相關(guān)的包
具體參考https://blog.csdn.net/weixin_42126327/article/details/127642279
1、安裝conda環(huán)境和相關(guān)包
# 一、安裝conda
# 1、首先,前往Anaconda官網(wǎng)(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的版本號,則安裝成功。
## 二、創(chuàng)建canda的虛擬開發(fā)環(huán)境 py36
# 1、創(chuàng)建canda的虛擬開發(fā)環(huán)境 py36
conda create --name py36 python=3.6
# 2、進(jìn)入虛擬開發(fā)環(huán)境
conda activate py36
# 3、退出虛擬環(huán)境
conda deactivate
## 三、安裝flask相關(guān)的包
conda install flask
conda install scikit-learn
2、搭建flask服務(wù)代碼
1、訓(xùn)練模型并保存模型
model.py
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import pickle
# 加載iris數(shù)據(jù)集,并進(jìn)行最簡單的訓(xùn)練過程,可以自行擴(kuò)展
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格式,準(zhǔn)備應(yīng)用層調(diào)用
pickle.dump(classifier, open("./model.pkl", "wb"))
2、啟動flask服務(wù)
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()))])
# 將預(yù)測結(jié)果放在字典中
output = {'prediction': int(prediction[0])}
# 將字典轉(zhuǎn)換為 JSON 格式并返回
return jsonify(output)
if __name__ == "__main__":
app.run(debug=True)
3、調(diào)用flask服務(wù)的客戶端代碼
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")
// 構(gòu)造JSON對象
val data = new JSONObject()
data.put("feature1", 1)
data.put("feature2", 2)
data.put("feature3", 3)
data.put("feature4", 4)
// 將JSON對象轉(zhuǎn)換為字符串
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
<!-- index.html -->
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>ML API</title>
</head>
<body>
<div class="login">
<h1>Flower Class Prediction</h1>
<form action="{{ url_for('predict')}}"method="post"> <!-- 這一塊是用戶輸入自定義數(shù)據(jù) -->
<input type="text" name="Sepal_Length" placeholder="Sepal_Length" required="required"/>
<input type="text" name="Sepal_Width" placeholder="Sepal_Width" required="required" />
<input type="text" name="Petal_Length" placeholder="Petal_Length" required="required"/>
<input type="text" name="Petal_Width" placeholder="Petal_Width" required="required" />
<button type="submit" class="btn btn-primary btn-block btn-large">Predict</button>
</form>
<br>
{{ prediction_text }} <!-- 這一塊是模型輸出結(jié)果 -->
</div>
</body>
</html>
3、flask服務(wù)的運(yùn)行
1、調(diào)試環(huán)境
# 1、啟動flask服務(wù)
python app_demo.py
# 2、客戶端請求flask服務(wù)
# 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、生產(chǎn)環(huán)境部署
uWSGI:uWSGI是一個高性能的WSGI服務(wù)器,支持多種編程語言和應(yīng)用程序框架,包括Flask。可以使用uWSGI來部署Flask服務(wù)
uwsgi安裝文章來源:http://www.zghlxwxcb.cn/news/detail-664342.html
conda install uwsgi --no-deps # 使用--no-deps選項:這將跳過依賴項
部署 參考:https://juejin.cn/post/7014036187937505317
配置文件uwsgi.ini 文件文章來源地址http://www.zghlxwxcb.cn/news/detail-664342.html
`
[uwsgi]
http = 127.0.0.1:5000
wsgi-file = app_demo.py
callable = app
`
準(zhǔn)備好配置文件后
# 啟動uwsgi服務(wù)
uwsgi --ini uwsgi.ini
# 停止uwsgi服務(wù)
uwsgi --stop uwsgi.pid
# 重啟uwsgi服務(wù)
uwsgi --reload uwsgi.pid
到了這里,關(guān)于flask模型部署教程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!