文章目录
项目场景
- 项目场景
- 算法服务
- 效果演示
- 网页部署
- 接口请求
- 请求地址
- 请求方式
- 请求参数
- 请求样例
- 单个参数
- 多个参数
- 线程优化
- 开放源码
基于 Python 开发了一个算法服务,如何通过 Flask 进行接口的部署及优化?
算法服务模拟一个最简单的算法服务:通过线性拟合解决回归问题。输入 x
,输出 y
。(仅供模拟测试,实际业务场景会很复杂)
y = ax+ b
- a:斜率
- b:截距
斜率和截距可通过配置文件 config.yaml
调节。
params:
a: 1
b: 1
效果演示
http://127.0.0.1:5000/
http://127.0.0.1:5000/api/1/
http://127.0.0.1:5000/api/1,2,3/
@app.route("/")
def hello_world() -> str:
"""Index
Returns:
str: Hello, World!
"""
return "Hello, World!"
@app.route("/api//", methods=["GET", "POST"])
def api(x: str, path: str = 'config.yaml') -> jsonify:
"""Interface of the project
Args:
x (str): Request parameter
path (str): Path of configuration file. Default to `config.yaml`
Returns:
jsonify: Format the data to JSON and return
"""
# Params
params = None
while params == None:
# When the yaml configuration file is being modified, it will return `None`
params = yaml.load(open(path), Loader=yaml.FullLoader)
a = params["params"]["a"]
b = params["params"]["b"]
# Params
# Algorithm
def func(x):
time.sleep(1)
y = a*float(x)+b
return y
# Algorithm
# Data
r = {"r": []}
x = x.split(",")
for i in x:
if i != "":
r["r"].append({"x": float(i), "y": func(i)})
else:
pass
# Data
return jsonify(r)
接口请求
请求地址
http://127.0.0.1:5000/api//
GET
或 POST
x
是字符串URL 参数
请求样例
单个参数
http://127.0.0.1:5000/api/1/
{
"r": [
{
"x": 1.0,
"y": 2.0
}
]
}
多个参数
http://127.0.0.1:5000/api/1,2,3/
{
"r": [
{
"x": 1.0,
"y": 2.0
},
{
"x": 2.0,
"y": 3.0
},
{
"x": 3.0,
"y": 4.0
}
]
}
线程优化
对于多参数请求,即多个 x
请求,响应时间很长。为此,可以做一个多线程优化。
with concurrent.futures.ThreadPoolExecutor() as p:
def temp(i):
if i != "":
r["r"].append({"x": float(i), "y": func(i)})
else:
pass
for i in x:
p.submit(temp, i)
开放源码
https://github.com/XavierJiezou/flask-algorithm-deploy