flask 部署算法模型

℡╲_俬逩灬. 提交于 2020-08-05 01:59:50

了解一点web知识,看一下flask教程就能使用flask写简单的demo. 在flask中加个载入模型函数,随服务启动将模型载入内存,将预测函数放进接收数据函数中,拿到数据即进行预测

#encoding:utf-8
from keras.applications import ResNet50
from PIL import Image
import numpy as np
import flask
import io
import tensorflow as tf

app = flask.Flask(__name__)
model = None

#载入模型
def load_model():
	global model
	model = ResNet50(weights="imagenet")
	global graph
	graph = tf.get_default_graph() #不加这个会报错

#预处理数据
def prepare_image(image):

	return image

#路由 预测
@app.route("/predict", methods=["POST"])
def predict():
	#获取http传来数据
	if flask.request.method == "POST":
		if flask.request.files.get("image"):
			#上传图片数据,也可上传文本,或者上传文件url,在预处理时读取
			image = flask.request.files["image"].read()
			image = Image.open(io.BytesIO(image))

	#数据预处理
	image = prepare_image(image)
	#模型预测
	with graph.as_default(): #不加这个会报错
		preds = model.predict(image)
	return preds

if __name__ == "__main__":
	load_model()
	# app.run(host, port, debug, options)
	# 默认值:host="127.0.0.1", port=5000, debug=False
	app.run(host="0.0.0.0", port=5500, debug=False, use_reloader=False)

常见requset请求方式:

import requests
#发送get请求
url = 'http://127.0.0.1:5000/predict'
data = {'stu_name':'小黑'} #请求数据
req = requests.get(url,params=data) #发送get请求
print(req.json()) #字典 单引号'
print(req.text) #string 双引号"

#发送post请求
url = 'http:///api/user/login'
data = {
	'username':'niuhanyang',
	'passwd':'aA123456'
} #请求数据
req = requests.post(url,data)#发送post请求
print(req.json())

#入参是json类型
url = 'http:///api/user/add_stu'
data =  {
	"name":"yyy",
	"grade":"9年级",
  }
req = requests.post(url,json=data)
print(req.json())

#添加cookie
url = 'http:///api/user/'
data = {'stu_id':123,'gold':1000}
cookie = {'hc123':'337ca4cc825302'}
req = requests.post(url,data,cookies=cookie)
print(req.json())
#添加header
url = 'http:///api/all_stu'
header = {
	'Referer':'http://api.nnzhp.cn/'
}
req = requests.get(url,headers = header)
print(req.json())

#上传文件
url = 'http:///api/file/file_upload'
data = {
  #  'file':open('baidu.html',encoding='utf-8')  #图片与excel是rb
	'file':open('.//1.jpg','rb')
}
req = requests.post(url,files = data,)
print(req.json())

#下载图片
url = 'http://127.0.0.1:5000/soup.jpg'
req = requests.get(url)
print(req.content) #返回的二进制
fw = open('m.mp3','wb')#二进制写模式wb
fw.write(req.content)

请求这部分搬运于:https://www.cnblogs.com/ymany/p/9040657.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!