小编给大家分享一下Flask如何搭建一个API服务器,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
① 获取手工制作作品列表。
请求格式:
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" } ] }
打开命令行,创建一份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()
1. 根目录测试
/twkk
2. 列表拉取测试
curl localhost:5000/twkk/list/hand_made
curl localhost:5000/twkk/list/drawing
curl localhost:5000/twkk/list/certificate
看完了这篇文章,相信你对“Flask如何搭建一个API服务器”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。