Flask实现Web服务调用Python程序
通过Web服务调用Python写的手写数字识别算法模型,得到手写数字识别结果。
项目场景:
项目需求:将客户端的请求经由Web服务器转发给Flask程序实例。
示例:通过Web服务调用Python写的手写数字识别算法模型,得到手写数字识别结果。
环境准备:
- Python环境不多说了
- 安装
flask
pip install flask
- 安装
waitress
pip install waitress
代码:
main.py
from flask import Flask
from predictNumber import predict
app=Flask(__name__)
@app.route('/predictNumber/', methods=['POST'])
def predict_number():
image = request.form["image"]
result = predict(image)
return {
"result": result
}
if __name__=='__main__':
app.debug=True
app.run(host='127.0.0.1',port=5000)
其中,手写数字识别的代码 predictNumber.py
赠送如下:
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from PIL import Image
import numpy as np
import base64
from io import BytesIO
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
def predict(image):
model = Net()
model.load_state_dict(torch.load("demo/model/mnist_cnn.pt"))
model.eval()
img = Image.open(image).convert('L')
img = img.resize((28, 28))
npimg1 = np.array(img)
flatten_img = npimg1.reshape(1, 1, 28, 28)
new_flatten_img = (255-flatten_img)/255.0
new_flatten_img = new_flatten_img.reshape(1, 1, 28, 28)
test_kwargs = {'batch_size': 1}
test_loader = torch.utils.data.DataLoader(new_flatten_img, **test_kwargs)
for data in test_loader:
data = data.to(torch.float32)
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
print(pred)
print(pred.item())
return pred.item()
启动该服务有两种方式
方式一:
通过运行Python脚本启动服务, run.py
代码如下:
from waitress import serve
import main
serve(main.app, host='127.0.0.1',port=5000)
直接运行 run.py
即可
python run.py
验证我们可通过postman发送请求,得到如下结果:

方式二:
通过 cmd 设置 mian.py 路径,我的 main.py
放在E:\pythonProject\下面,大家自行调整。
set FLASK_APP=E:\pythonProject\main.py
然后使用以下指令启动服务:
[En]
Then start the service with the following directive:
flask run
效果如下:

以上是简单版的完整流程。在下面添加一些其他说明。
[En]
The above is the complete process of the simple version. Add some additional instructions below.
Flask程序必须创建一个程序实例。参见上面第一个代码 main.py
中 app = Flask(__name__)
即为实例。
Web服务器把接收到的所有客户端请求,转交给Web服务器网关接口对象处理。需要提供的参数只有一个,就是程序主模块或包的名字,一般就是Python的name变量。
客户端的请求经由Web服务器转发给Flask程序实例。程序实例需要URL到具体代码的映射关系。这个映射关系称为路由。
Flask中最简单的路由定义方式是app.route修饰器。
上面的路由定义,把根路径和predictNumber函数关联起来,如果部署程序的服务器域名是 http://127.0.0.1:5000/,那么浏览器中输入 http://127.0.0.1:5000/predictNumber/ 就会触发这个函数。
函数的返回值称为响应,是客户端接收到的内容。这样如果客户端是Web浏览器,响应就是给客户看的文档。
在下面的博客文章中有一个非常详细和完整的介绍以供参考。
[En]
There is a very detailed and complete introduction in the following blog post for reference.
有关多个并发呼叫业务,请参阅:
[En]
For more than one concurrent call service, please see:
多并发调用Pytorch的坑:
Flask+gunicorn部署深度学习报错gunicorn: error: argument -b: invalid int value ‘0.0.0.0:8000’
Original: https://blog.csdn.net/qq_39691492/article/details/122088475
Author: 小白白程序员
Title: Flask实现Web服务调用Python程序
相关阅读
Title: Python根据csv绘制多折线图(内含批量读取+自定义坐标标签+阴影处理)
实现功能
1.从csv中读取数据
2.数据清洗(大小超出范围的异常值处理)
3.数据累积处理(将每日数据处理为历史累积值)
4.绘制多折线图
0.导入相关包import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
1.从csv格式文件中读取数据
site='3'
band="NDVI"
sentinel="2-L2A"
path= '../data/dataset/Train_region_csv/S{}/csv/{}-{}.csv'.format(sentinel,site, band)
pixel_csv = pd.read_csv(path, index_col = 0)
拓展:批量读取csv文件,存储为DataFrame格式
(1)从文件夹中读取 全部 / 指定部分文件名 的文件
import glob
sentinel = "2-L2A"
site = '3'
path= '../data/dataset/Train_region_csv/S{}/csv/'.format(sentinel)
file = glob.glob(os.path.join(path,"*.csv"))
file_3 = glob.glob(os.path.join(path,"3-*.csv"))
file_x = glob.glob(os.path.join(path,"{}-*.csv".format(site)))
print("file length:",len(file))
print(file)
(2)批量读取
list2dataframe=[]
for path_file in file:
list2dataframe.append(pd.read_csv(path_file,index_col = 0))
(3)整合(1)(2),封装为函数
def Dataloading_csv (folder_path):
site='3'
file = glob.glob(os.path.join(folder_path,"{}-*.csv".format(site)))
list2dataframe=[]
for path_file in file:
list2dataframe.append(pd.read_csv(path_file,index_col = 0))
return list2dataframe
2.数据清洗-删除超过范围的异常值
for j in range(pixel_csv.shape[1]):
for i in range(pixel_csv.shape[0]):
if (pixel_csv.iloc[i,j]> 1 or pixel_csv.iloc[i,j] < 0):
pixel_csv.iloc[i,:]=np.nan
3.数据处理-将每日数据处理为历史累积值
for j in range(1,pixel_csv.shape[1]):
for i in range(pixel_csv.shape[0]):
x=pixel_sum.iloc[i,j]
pixel_sum.iloc[i,j]=x+pixel_sum.iloc[i,j-1]
4.绘制多折线图
对DataFrame使用describe函数,获得DataFrame的初步统计信息,其中包含min,max,mean

def plot_min_max_mean(data_desc):
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(data_desc.index, data_desc.iloc[:,7],color='crimson',label='Max')
ax.plot(data_desc.index, data_desc.iloc[:,1],color='c',label='Mean')
ax.plot(data_desc.index, data_desc.iloc[:,3],color='royalblue',label='Min')
ax.set_xticks([0,12,25,37,49,62,74,84])
ax.set_xticklabels(['04-01', '05-01', '06-01', '07-01', '08-01', '09-01','10-01','11-01'],rotation=45,fontsize=12)
plt.title('Site-3',fontsize=16)
plt.xlabel('Dates',fontsize=14)
plt.ylabel('EVI',fontsize=14)
plt.fill_between(data_desc.index, data_desc.iloc[:,7], data_desc.iloc[:,3], facecolor="orange",alpha=0.1)
plt.legend()
plt.show()
Original: https://blog.csdn.net/weixin_44114632/article/details/119856671
Author: 雨霁夜白
Title: Python根据csv绘制多折线图(内含批量读取+自定义坐标标签+阴影处理)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/299436/
转载文章受原作者版权保护。转载请注明原作者出处!