Posted in Python onMay 28, 2021
一、API列表
1. 获取作品列表
① 获取手工制作作品列表。
请求格式:
http://api.mculover666.cn:9999/twkk/list/hand_made
返回结果:
{
goods_num: 3,
goods_item: [
{
goods_id: 1,
goods_name: "goods1",
goods_img_url: "xxx"
},
{
goods_id: 2,
goods_name: "goods1",
goods_img_url: "xxx"
},
{
goods_id: 3,
goods_name: "goods1",
goods_img_url: "xxx"
}
]
}
② 获取绘画作品列表。
请求格式:
http://api.mculover666.cn:9999/twkk/list/drawing
返回结果:
{
goods_num: 3,
goods_item: [
{
goods_id: 4,
goods_name: "goods1",
goods_img_url: "xxx"
},
{
goods_id: 5,
goods_name: "goods1",
goods_img_url: "xxx"
},
{
goods_id: 6,
goods_name: "goods1",
goods_img_url: "xxx"
}
]
}
③ 获取证书列表
请求格式:
http://api.mculover666.cn:9999/twkk/list/certificate
返回结果:
{
goods_num: 3,
goods_item: [
{
goods_id: 6,
goods_name: "goods1",
goods_img_url: "xxx"
},
{
goods_id: 7,
goods_name: "goods1",
goods_img_url: "xxx"
},
{
goods_id: 8,
goods_name: "goods1",
goods_img_url: "xxx"
}
]
}
二、安装Flask
打开命令行,创建一份python虚拟环境:
python3 -m venv venv
在当前终端激活虚拟环境:
.\venv\Scripts\Activate.ps1
激活虚拟环境后,安装Flask:
pip install Flask
查看安装结果:
pip list
编写一个HelloWorld测试一下:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Helloworld'
if __name__ == '__main__':
app.run()
Flask参考教程:https://www.w3cschool.cn/flask/
三、代码实现
# 导入Flask类
from flask import Flask, redirect, url_for, render_template
import json
# 使用当前模块的名称构建Flask app
app = Flask(__name__)
# 装饰器,设置根目录url调用函数
@app.route('/twkk')
def index():
version = "v1.0.0"
return render_template('index.html', app_version=version)
# 管理员url
@app.route('/twkk/admin')
def hello_admin():
return 'Hello admin'
# 获取分类列表
@app.route('/twkk/list/<category>', methods=["GET"])
def get_item_list(category):
#读取json文件内容
try:
if category == 'drawing':
with open('drawing.json', 'r') as fp:
json_data = json.load(fp)
res_data = json.dumps(json_data)
return res_data
elif category == 'hand_made':
with open('hand_made.json', 'r') as fp:
json_data = json.load(fp)
res_data = json.dumps(json_data)
return res_data
elif category == 'certificate':
with open('certificate.json', 'r') as fp:
json_data = json.load(fp)
res_data = json.dumps(json_data)
return res_data
except:
return ""
# 运行程序
if __name__ == '__main__':
app.run()
四、API测试
1. 根目录测试
/twkk
2. 列表拉取测试
curl localhost:5000/twkk/list/hand_made
curl localhost:5000/twkk/list/drawing
curl localhost:5000/twkk/list/certificate
到此这篇关于Flask搭建一个API服务器的步骤的文章就介绍到这了,更多相关Flask搭建API服务器内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!
Flask搭建一个API服务器的步骤
- Author -
Mculover666声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@