zoukankan      html  css  js  c++  java
  • 基于Flask的 api(三)

    使用flask的RESTful扩展库 flask-restful

    安装

    pip install flask-restful

    eg:

    最简单的api

    from flask import Flask
    from flask_restful import Api, Resource
    
    app = Flask(__name__)
    api = Api(app)
    
    class HelloWorld(Resource):
        def get(self):
            return {'hello': 'world'}
    api.add_resource(HelloWorld, '/')
    
    if __name__ == "__main__":
        app.run(debug=True,port=5000)

    测试

    $ curl -i http://localhost:5000
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100    25  100    25    0     0     25      0  0:00:01 --:--:--  0:00:01   123HTTP/1.0 200 OK
    Content-Type: application/json
    Content-Length: 25
    Server: Werkzeug/1.0.1 Python/3.7.7
    Date: Tue, 24 Nov 2020 04:31:12 GMT
    
    {
        "hello": "world"
    }

    restful api

    from flask import Flask
    from flask_restful import reqparse, abort, Api, Resource
    
    app = Flask(__name__)
    api = Api(app)
    
    tasks = [
        {
            'id': 1,
            'title': u'Buy groceries',
            'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
            'done': False
        },
        {
            'id': 2,
            'title': u'Learn Python',
            'description': u'Need to find a good Python tutorial on the web',
            'done': False
        }
    ]
    
    def abort_if_todo_doesnt_exist(task,id):
        if len(task) ==0:
            abort(404, message="task {} doesn't exist".format(id))
    
    parser = reqparse.RequestParser()
    parser.add_argument('title')
    parser.add_argument('description')
    parser.add_argument('done')
    
    # (put/get/delete)Task
    class Task(Resource):
        def get(self, id):
            task = list(filter(lambda t: t['id']==id,tasks))
            abort_if_todo_doesnt_exist(task,id)
            return task
    
        def delete(self, id):
            task = list(filter(lambda t: t['id']==id,tasks))
            abort_if_todo_doesnt_exist(task,id)
            tasks.remove(task[0])
            return {'result': True,'list':tasks}
    
        def put(self, id):
            task = list(filter(lambda t: t['id']==id,tasks))
            abort_if_todo_doesnt_exist(task,id)
            args = parser.parse_args()
            task[0]['title'] = args['title']
            task[0]['description'] = args['description']
            task[0]['done'] = args['done']
            return task, 201
    
    #(post/get)TaskList
    class TaskList(Resource):
        def get(self):
            return tasks
    
        def post(self):
            args = parser.parse_args()
            task = {
                'id': tasks[-1]['id'] + 1,
                'title': args['title'],
                'description': args['description'],
                'done': False
            }
            tasks.append(task)
            return task, 201
    
    # 设置路由
    api.add_resource(TaskList, '/tasks')
    api.add_resource(Task, '/tasks/<int:id>')
    
    if __name__ == "__main__":
        app.run(debug=True,port=5000)

    说明:

      RequestParser参数解析类,可以很方便的解析请求中的-d参数,并进行类型转换

      使用add_resource设置路由

      

  • 相关阅读:
    VTK初学一,动画加AVI录制终于做出来了
    QCamera获取摄像头图像(转载)
    VTK初学一,比较常见的错误2
    myeclipse2014鼠标单击后光标位置背景底色为白色太难看,行号显示
    记一次跟二房东公司(非中介个人房源无中介费)租房的经历
    求16进制数据或运算后的值(即多个16进制相加的和)
    error LNK2001: 无法解析的外部符号 "public: char * __thiscall
    如何利用指向数组的指针得到数组元素个数?
    C++判断字符串是否为空的一个小问题
    C++开发中BYTE类型数组转为对应的字符串
  • 原文地址:https://www.cnblogs.com/baby123/p/14029739.html
Copyright © 2011-2022 走看看