Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚠️ Python编写简易API #89

Open
reng99 opened this issue Mar 24, 2021 · 0 comments
Open

⚠️ Python编写简易API #89

reng99 opened this issue Mar 24, 2021 · 0 comments
Labels
blog a single blog

Comments

@reng99
Copy link
Owner

reng99 commented Mar 24, 2021

flask_restful_banner.png

本文约550字,将耗费您约4⃣️分钟

所有的操作,仅在mac系统上实操过

前期准备

创建一个虚拟环境:

$ mkdir flask_restful
$ cd flask_restful
$ python3 -m venv venv

激活虚拟环境:

$ . venv/bin/activate

虚拟环境退出:

$ deactivate

安装flaskflask_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": {}
}

后话

@reng99 reng99 added the blog a single blog label Mar 24, 2021
@reng99 reng99 changed the title flask restful 初探 ⚠️ Python编写简易API Mar 25, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
blog a single blog
Projects
None yet
Development

No branches or pull requests

1 participant