本文约550字,将耗费您约4⃣️分钟~
所有的操作,仅在
mac
系统上实操过
前期准备
创建一个虚拟环境:
$ mkdir flask_restful
$ cd flask_restful
$ python3 -m venv venv
激活虚拟环境:
$ . venv/bin/activate
虚拟环境退出:
$ deactivate
安装flask
和flask_restful
:
$ pip install flask
$ pip install flask_restful
项目接口模拟
在项目的根目录下面新建文件api.py
,在此文件中进行数据的增删改查。
⚠️ 这里使用到的数据为模拟数据,并未连接数据库
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
USER_LIST = [{'id': 1, 'name': 'jimmy'}]
class UserListApi(Resource):
def get(self):
return {'code': 10000, 'msg': 'get list success', 'data': USER_LIST}
def post(self):
json_data = request.get_json()
new_id = len(USER_LIST) + 1
USER_LIST.append({'id': new_id, 'name': json_data.get('name')})
return jsonify({'code': 10000, 'msg': 'add user success', 'data': USER_LIST[new_id-1]})
class UserApi(Resource):
def get(self, id):
return {'code': 10000, 'msg': 'get user success', 'data': {}}
def put(self, id):
return {'code': 10000, 'msg': 'update user success', 'data': {}}
def delete(self, id):
return {'code': 10000, 'msg': 'remove user success', 'data': {}}
api.add_resource(UserListApi, '/users')
api.add_resource(UserApi, '/users/<int:id>')
if __name__ == '__main__':
app.run(debug=True)
之后运行应用:
$ export FLASK_APP=api.py
$ export FLASK_ENV=development
$ flask run
看到下面的输出,说明运行成功了:
* Serving Flask app "flaskr" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 577-682-777
项目接口验证
在上面的代码中,我们对users
进行了相关的增删改查,下面我们来验证下:
- 新增一个用户
$ curl http://127.0.0.1:5000/users -X POST -H "Content-Type:application/json" -d '{"name": "tom"}'
{
"code": 10000,
"data": {
"id": 2,
"name": "tom"
},
"msg": "add user success"
}
- 查询整个用户列表
$ curl http://127.0.0.1:5000/users
{
"code": 10000,
"msg": "get list success",
"data": [
{
"id": 1,
"name": "jimmy"
},
{
"id": 2,
"name": "tom"
}
]
}
- 更新一个用户
$ curl http://127.0.0.1:5000/users/1 -X PUT
{
"code": 10000,
"msg": "update user success",
"data": {}
}
- 获取一个用户
$ curl http://127.0.0.1:5000/users/1
{
"code": 10000,
"msg": "get user success",
"data": {}
}
- 删除一个用户
$ curl http://127.0.0.1:5000/users/1 -X DELETE
{
"code": 10000,
"msg": "remove user success",
"data": {}
}